본문 바로가기
BACKEND/PostgreSQL

PostgreSQL 설치

by 드로니뚜벅이 2022. 7. 14.

Windows

설치 프로그램을 다운로드하려면 https://www.postgresql.org/download/windows/ 페이지에서 "Download the installer"를 클릭하세요. 그러면 EDB 다운로드 페이지로 이동합니다.

(EDB는 Windows PostgreSQL 사용자를 위한 지원 및 서비스를 제공하는 회사입니다.)

Windows x86-64 버전용 최신 PostgreSQL을 선택해서 설치프로그램을 다운로드한 후 PostgreSQL, pgAdmin 및 추가 컴포넌트를 설치합니다.

설치를 시작합니다.

<Next>

<Next>

모든 옵션을 선택한 후 <Next> 를 클릭합니다.

데이터 디렉토리를 지정합니다. (기본경로: C:\Program Files\PostgreSQL\16\data)

<Next>를 누른 후 데이터베이스 슈퍼유저의 비밀번호를 입력합니다.

<Next> 버튼을 눌러 Port 번호를 입력하세요. 기본값은 5432입니다.

 

<Next> 버튼을 눌러 Locale를 선택합니다.

<Next> 버튼을 눌러 설치 요약정보를 확인합니다.

 

이제 설치 준비가 모두 끝났습니다. 설치를 합니다.

설치가 완료되면 아래 화면에서 체크박스에 체크가 된 상태로 <Finish>를 누릅니다.

Stack Builder가 시작되면 위에서 설치한 버전을 선택한 후 <Next> 버튼을 누릅니다.

추가할 응용프로그램을 선택합니다.

1) "Add-ons, tools and utilities" -> "EDB Language Pack" 체크박스 선택

2) "Spatial Extensions" -> "PostGIS..." 체크박스 선택

더보기

PostGIS 3.4.1 bundle includes PostGIS 3.4.1 w GDAL 3.7.1 (SQLite 3.30.1, OpenJPEG 2.4.0, Expat 2.4.8, FreeXL 1.0.6, Arrow 13.0.0)  , GEOS 3.12.1, Proj 8.2.1, pgRouting 3.6.0,  osm2pgrouting 2.3.8, ogr_fdw 1.1.4 spatial foreign data wrapper extension, and pgPointcloud 1.2.4, h3-pg 4.1.3, MobilityDb 1.1.0beta1.
https://postgis.net/2023/11/PostGIS-Patch-Releases/

PostGIS "spatially enables" the PostgreSQL server, allowing it to be used as a backend spatial database for geographic information systems (GIS). PostGIS follows the OpenGIS "Simple Features Specification for SQL" and has been certified as compliant with the "Types and Functions" profile. 

https://github.com/pgRouting/pgrouting/releases/tag/v3.6.0
pgRouting extensions PostGIS for building routing applications

https://github.com/pgRouting/osm2pgrouting
osm2pgRouting for loading OSM data into pgrouting

https://github.com/pramsey/pgsql-ogr-fdw
ogr_fdw allows you to query flat files, relational databases, and web services to name a few.  Spatial columns get transformed to PostGIS geometry columns.

https://github.com/pgpointcloud/pointcloud
pgPointcloud introduces specialty types for storing point cloud data loaded from LIDAR.

https://github.com/zachasme/h3-pg
Uber h3 api with conversion of h3 index to postgis geometries.

https://github.com/MobilityDB/MobilityDB
MobilityDb for managing spatial trajectories

설치를 합니다.

 

Ubuntu (Linux)

기본 버전 설치하기

Ubuntu 20.04에서 PostgreSQL를 설치하면 12.14 버전이 설치됩니다.

$ sudo apt update && sudo apt upgrade -y
$ 
$ sudo apt install software-properties-common apt-transport-https wget -y
$ sudo apt install postgresql postgresql-contrib
$ psql --version
psql (PostgreSQL) 12.14 (Ubuntu 12.14-0ubuntu0.20.04.1)

 

최신 버전 설치하기

최신 버전을 설치하고자 한다면 저장소를 추가해 줘야 합니다.

(PostgreSQL package for Debian and Ubuntu Wiki를 참고하세요.)

$ sudo apt update && sudo apt upgrade -y

// $ sudo apt install software-properties-common apt-transport-https wget -y
$ sudo apt install curl ca-certificates gnupg -y

// Import the repository signing key
// wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
$ curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/apt.postgresql.org.gpg >/dev/null

//Create /etc/apt/sources.list.d/pgdg.list. The distributions are called codename-pgdg.
$ sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

// Update the package lists
$ sudo apt update

// Finally, update the package lists, and start installing packages:
// $ sudo apt -y install postgresql-15 // If you want to install a specific version
$ sudo apt -y install postgresql

// Alternately, you can install postgresql-common package
$ sudo apt install postgresql-common
$ sudo sh /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh

 

설치 확인 및 활성화

1. PostgreSQL 설치가 완료되었으면 버전 및 활성화 상태를 확인합니다.

$ psql --version
psql (PostgreSQL) 15.2 (Ubuntu 15.2-1.pgdg20.04+1)
$
$ systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pre>
     Active: active (exited) since Thu 2022-07-14 08:22:46 KST; 1h 44min ago
    Process: 1489 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 1489 (code=exited, status=0/SUCCESS)

 7월 14 08:22:46 mapit systemd[1]: Starting PostgreSQL RDBMS...
 7월 14 08:22:46 mapit systemd[1]: Finished PostgreSQL RDBMS.
 $

 

2. 서비스 데몬 LISTEN 상태를 확인합니다. (PostgreSQL은 기본으로 TCP 5432 포트 사용)

$ sudo ss -ntlp                                                                                                                   
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process                                         
LISTEN      0           4096             127.0.0.53%lo:53                  0.0.0.0:*         users:(("systemd-resolve",pid=1073,fd=13))     
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*         users:(("sshd",pid=1258,fd=3))                 
LISTEN      0           5                    127.0.0.1:631                 0.0.0.0:*         users:(("cupsd",pid=1128,fd=7))                
LISTEN      0           244                  127.0.0.1:5432                0.0.0.0:*         users:(("postgres",pid=41132,fd=5))            
LISTEN      0           2                        [::1]:3350                   [::]:*         users:(("xrdp-sesman",pid=1260,fd=7))          
LISTEN      0           128                       [::]:22                     [::]:*         users:(("sshd",pid=1258,fd=4))                 
LISTEN      0           5                        [::1]:631                    [::]:*         users:(("cupsd",pid=1128,fd=6))                
LISTEN      0           2                            *:3389                      *:*         users:(("xrdp",pid=1275,fd=11))

위처럼 127.0.0.1:5432로 표시된다면 로컬(설치된 작업 PC)에서만 접속되고 현재 외부접속은 허용하지 않는다는 의미입니다.

프로젝트 목적에 따라 외부접속이 필요하다면 설정파일(/etc/postgresql/15/main/postgresql.conf)을 수정해 주어야 합니다. 관련 내용은 아래 "방화벽 구성" 내용을 확인해 주세요.

 

3. 프로세스 실행여부를 확인합니다.

$ ps -ef | grep post                    
postgres   41132       1  0 13:08 ?        00:00:00 /usr/lib/postgresql/15/bin/postgres -D /var/lib/postgresql/15/main -c config_file=/etc/postgresql/15/main/postgresql.conf
postgres   41133   41132  0 13:08 ?        00:00:00 postgres: 15/main: checkpointer 
postgres   41134   41132  0 13:08 ?        00:00:00 postgres: 15/main: background writer 
postgres   41136   41132  0 13:08 ?        00:00:00 postgres: 15/main: walwriter 
postgres   41137   41132  0 13:08 ?        00:00:00 postgres: 15/main: autovacuum launcher 
postgres   41138   41132  0 13:08 ?        00:00:00 postgres: 15/main: logical replication launcher

 

4. 패키지가 설치되었는지 확인합니다.

$ dpkg -l | grep postgres
ii  postgresql-15                              15.2-1.pgdg20.04+1                       amd64        The World's Most Advanced Open Source Relational Database
ii  postgresql-client-15                       15.2-1.pgdg20.04+1                       amd64        front-end programs for PostgreSQL 15
ii  postgresql-client-common                   247.pgdg20.04+1                          all          manager for multiple PostgreSQL client versions
ii  postgresql-common                          247.pgdg20.04+1                          all          PostgreSQL database-cluster manager

 

 

PostgreSQL이 활성화되어 있지 않으면 활성화 시켜줘야 합니다.

$ systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pre>
     Active: inactive (dead) since Thu 2022-07-14 10:11:37 KST; 5s ago
    Process: 1489 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 1489 (code=exited, status=0/SUCCESS)

 7월 14 08:22:46 mapit systemd[1]: Starting PostgreSQL RDBMS...
 7월 14 08:22:46 mapit systemd[1]: Finished PostgreSQL RDBMS.
 7월 14 10:11:37 mapit systemd[1]: postgresql.service: Succeeded.
 7월 14 10:11:37 mapit systemd[1]: Stopped PostgreSQL RDBMS.
 
 $ sudo systemctl enable postgresql --now

 

PostgreSQL 서비스 명령

1) PostgreSQL 서버 시작

$ sudo systemctl start postgresql

2) PostgreSQL 서버 중지

$ sudo systemctl stop postgresql

3) PostgreSQL 서버 재시작

$ sudo systemctl restart postgresql

4) PostgreSQL 상태 정보 보기

$ systemctl status postgresql

5) PostgreSQL 서버 재로드

$ sudo systemctl reload postgresql

 

간단히 사용해 보기

PostgreSQL 설치가 완료되면 postgres라는 관리 계정이 자동으로 생성됩니다.

$ sudo -i -u postgres
postgres@mapit:~$ psql
psql (15.2 (Ubuntu 15.2-1.pgdg20.04+1))
도움말을 보려면 "help"를 입력하십시오.

postgres=#

사용자 계정을 변경하지 않고 postgres 데이터베이스와 상호 작용하기 위한 다른 방법으로 "sudo" 명령을 사용하여 직접 연결할 수 있습니다.

$ sudo -u postgres psql
psql (14.4 (Ubuntu 14.4-1.pgdg20.04+1))
도움말을 보려면 "help"를 입력하시오.

postgres=#

 

PostgreSQL 을 빠져 나오려면 "\q" 명령어를 사용합니다.

postgres=# \q
postgres@mapit:~$ exit

 

사용자를 추가하거나 삭제하려면 create와 drop 명령어를 사용합니다.

postgres=# create user user1;
CREATE ROLE
postgres=# \du
Role name      |    list of roles Attributes            | Memober of
---------------+----------------------------------------+-----------
postgres       | Superuser, Create role, Create DB, ..  | {}
user1          |                                        | {}

postgres=# drop user user1;

 

방화벽(UFW) 구성

PostgreSQL이 기본 포트에서 통신할 수 있도록 UFW 방화벽 규칙을 생성해야 합니다. 즉, 5432, localhost 이외의 다른 것을 사용하려는 경우에 필요합니다.

UFW 방화벽 활성화 상태를 확인합니다.

$ sudo ufw enable
$ sudo ufw allow proto tcp from 192.168.6.0/24 to any port 5432

PostgreSQL에 대한 기본 접근 권한은 로컬(localhost, 127.0.0.1)로 설정되어 있기 때문에 위 방화벽 설정으로 수신하기 위해서는 설정파일 변경이 필요합니다.

아래 설정 항목 중  "listen_address"을 변경해 줍니다. ('localhost' -> '*')

#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
port = 5432                             # (change requires restart)
max_connections = 100                   # (change requires restart)

설정 파일을 수정했다면 PostgreSQL을 재시작해 주어야 합니다.

$ sudo systemctl restart postgresql
$ sudo ss -ntlp                                  
State     Recv-Q    Send-Q    Local Address:Port  Peer Address:Port  Process                                                                                          
LISTEN    0         5            127.0.0.1:631    0.0.0.0:*          users:(("cupsd",pid=1129,fd=7))                                                                 
LISTEN    0         244           0.0.0.0:5432    0.0.0.0:*          users:(("postgres",pid=17656,fd=5))                                                             
LISTEN    0         4096      127.0.0.53%lo:53    0.0.0.0:*          users:(("systemd-resolve",pid=1040,fd=13))                                                      
LISTEN    0         128             0.0.0.0:22    0.0.0.0:*          users:(("sshd",pid=1263,fd=3))                                                                  
LISTEN    0         5                [::1]:631       [::]:*          users:(("cupsd",pid=1129,fd=6))                                                                 
LISTEN    0         244              [::]:5432       [::]:*          users:(("postgres",pid=17656,fd=6))                                                             
LISTEN    0         2                   *:3389          *:*          users:(("xrdp",pid=1290,fd=11))                                                                 
LISTEN    0         511                   *:80          *:*          users:(("apache2",pid=1295,fd=4),("apache2",pid=1294,fd=4),("apache2",pid=1292,fd=4))           
LISTEN    0         2               [::1]:3350       [::]:*          users:(("xrdp-sesman",pid=1278,fd=7))                                                           
LISTEN    0         128                [::]:22       [::]:*          users:(("sshd",pid=1263,fd=4))

0.0.0.0:5432[::]:5432를 통해 이제 외부 접속이 가능하다는 것을 확인할 수 있습니다.

 

외부에서 모든 계정으로 모든 데이터베이스 접속을 허용하려면 아래와 같이 PostgreSQL의 보안 설정 파일인 pg_hba.conf을 수정해 주어야 합니다. (/etc/postgresql/14/main/pg_hba.conf)

파일명에서 알 수 있듯이 hba(host-based authentication)는 데이터베이스 클러스터의 데이터 디렉토리에 저장되는 구성 파일로서 클라이언트 인증을 제어합니다.

# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

아시죠? 설정 파일을 수정했으면 PostgreSQL을 재시작해야 합니다. (systemctl restart postgresql)

 

설치 시 이슈

$ sudo -i -u postgres        
[sudo] password for yunny: 
postgres@admapserver:~$ 
postgres@admapserver:~$ 
postgres@admapserver:~$ psql
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
	Is the server running locally and accepting connections on that socket?

여러 가지 원인이 있으나 위 에러는 "/etc/postgresql/14"와 같이 설치된 해당 버전(12, 13, 14 or 15)이 없는 경우에 발생했습니다.

$ sudo apt install postgresql-15           
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  postgresql-client-15 postgresql-client-common postgresql-common sysstat
Suggested packages:
  postgresql-doc-15 isag
The following NEW packages will be installed:
  postgresql-15 postgresql-client-15 postgresql-client-common postgresql-common sysstat
0 upgraded, 5 newly installed, 0 to remove and 1 not upgraded.
Need to get 17.9 MB/18.2 MB of archives.
After this operation, 61.5 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://mirror.kakao.com/ubuntu focal-updates/main amd64 sysstat amd64 12.2.0-2ubuntu0.2 [448 kB]
Get:2 http://apt.postgresql.org/pub/repos/apt focal-pgdg/main amd64 postgresql-client-15 amd64 15.2-1.pgdg20.04+1 [1,623 kB]
Get:3 http://apt.postgresql.org/pub/repos/apt focal-pgdg/main amd64 postgresql-15 amd64 14.7-1.pgdg20.04+1 [15.8 MB]
Fetched 17.9 MB in 39s (463 kB/s)
.
.
.
Error: The locale requested by the environment is invalid:
  LANG: en_UR.UTF-8
Error: could not create default cluster. Please create it manually with

  pg_createcluster 15 main --start

or a similar command (see 'man pg_createcluster').
update-alternatives: using /usr/share/postgresql/14/man/man1/postmaster.1.gz to provide /usr/share/man/ma
n1/postmaster.1.gz (postmaster.1.gz) in auto mode
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for systemd (245.4-4ubuntu3.20) ...

수동으로 pg_createcluster 명령어로 기본 클러스터(15/main)를 생성해 주니 정상적으로 실행이 되네요.

$ sudo pg_createcluster 15 main --start
Creating new PostgreSQL cluster 15/main ...
/usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main --auth-local peer --auth-host scram-sha-256 --no-instructions
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/15/main ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Asia/Seoul
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok
Ver Cluster Port Status Owner    Data directory              Log file
14  main    5432 online postgres /var/lib/postgresql/15/main /var/log/postgresql/postgresql-15-main.log

이제 접속하면 정상적으로 접속이 되네요.

[sudo] password for yunny: 
postgres@admapserver:~$ psql
psql (15.2 (Ubuntu 15.2-1.pgdg20.04+1))
Type "help" for help.

postgres=#

 

PostgreSQL 삭제

apt purge와 autoremove를 사용해서 PostgreSQL을 삭제할 수 있습니다. (apt remove를 사용해도 되지만 그냥 깔끔히 지우고 싶어서 purge 옵션을 사용했습니다.)

$ sudo apt purge postgresql # postgresql -> postgresql-12, 14 or 15
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  postgresql-common sysstat
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED:
  postgresql-14*
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 51.5 MB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 384861 files and directories currently installed.)
Removing postgresql-14 (14.7-1.pgdg20.04+1) ...
Processing triggers for postgresql-common (247.pgdg20.04+1) ...
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
  en_us
  ko
Removing obsolete dictionary files:
(Reading database ... 383321 files and directories currently installed.)
Purging configuration files for postgresql-14 (14.7-1.pgdg20.04+1) ...
Dropping cluster main...

$ sudo apt autoremove
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  postgresql-client-14 postgresql-client-common postgresql-common sysstat
0 upgraded, 0 newly installed, 4 to remove and 0 not upgraded.
After this operation, 9,939 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 383321 files and directories currently installed.)
Removing postgresql-client-14 (14.7-1.pgdg20.04+1) ...
Removing postgresql-common (247.pgdg20.04+1) ...
Removing 'diversion of /usr/bin/pg_config to /usr/bin/pg_config.libpq-dev by postgresql-common'
Removing postgresql-client-common (247.pgdg20.04+1) ...
Removing sysstat (12.2.0-2ubuntu0.2) ...
Processing triggers for man-db (2.9.1-1) ...

 

참고사이트

 

 

'BACKEND > PostgreSQL' 카테고리의 다른 글

Ubuntu PostgreSQL 백업(backup) 및 복구(restore)  (0) 2023.03.12
Linux(Ubuntu) pgAdmin4 설치  (0) 2023.03.11
pgRouting 설치  (0) 2023.01.31
PostGIS 설치  (0) 2023.01.31
PostgreSQL 개요  (0) 2022.07.13