Database/PostgreSQL

PostgreSQL initdb 초기화 / 초기 설정 방법

MORAN9 2024. 4. 16. 12:45
반응형

 

💡  이 게시물은 입문자 분들 비율이 높을 것 같아, 부족하지만 상세 설명 덧붙여 진행하겠습니다.

 

 

[ 검색하셨을만한 에러 ]

psql: error: connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?

Job for postgresql-15.service failed because the control process exited with error code.
See "systemctl status postgresql-15.service" and "journalctl -xeu postgresql-15.service" for details.

+ 에러의 범위가 넓은 편이라, 이전에는 실행되었고, db 삭제한 적 없다 이러신 분들은 해당되지 않습니다.

 

 

[ 작업 환경 ]

- Docker Container

- Rockylinux:9.2

- PostgreSQL 15 Server

+ 같은 계열인 CentOS의 경우도 비슷할 듯 합니다.

 


 

PostgreSQL-15 설치

낮은 버전도 무관하시다면, yum install postgresql 이런 식으로도 가능할 듯 합니다.

# 아래 명령어는 둘 중 하나만 해당되는 아키텍쳐로 다운로드
# 맥북 M1+의 경우: aarch64
yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-aarch64/pgdg-redhat-repo-latest.noarch.rpm
# 데스크탑의 경우: x86_64
yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# 다른 버전의 PostgreSQL로 설치될 모듈들 비활성화하는 명령어
yum -qy module disable postgresql

# 설치
yum install -y postgresql15-server

 

PostgreSQL 유저 변경

[root@0c6f22bdea32 ~]# passwd
Changing password for user root.
New password: 
Retype new password:

root 암호가 설정되어있지 않은 경우, root로 되돌아오기 어려운 경우가 있었기 때문에 미리 설정하고 시작합니다.

 

[root@0c6f22bdea32 /]# su - postgres
Last login: Fri Apr 12 16:49:27 KST 2024 on pts/2

+ postgres 계정은 사용자가 별도로 만드는 계정이 아니라, postgreSQL 설치시 자동으로 만들어지는 계정입니다.

postgres는 보안의 이유로 root보다는 postgres 유저로 초기화를 진행하도록 되어있습니다.

 


 

보안 상의 이유?

아시는 내용이시거나, 궁금하지 않으시면 이 블럭은 넘어가셔도 됩니다. 저도 쓰면서 긴가민가합니다.

 

 

[ 에러 내용 ]  권한이 없으므로, root 계정으로 명령어를 실행할 수 없다는 내용.

[root@0c6f22bdea32 /]$ /usr/pgsql-15/bin/initdb
# initdb: error: cannot be run as root
# initdb: hint: Please log in (using, e.g., "su") as the (unprivileged) user that will own the server process.

때문에 만약 root 유저로 같은 작업을 진행하려는 경우, 위와 같은 에러를 볼 수 있습니다.

 

 

+ root 대신 postgres 계정을 사용하는 이유:

# 현재 실행 중인 프로세스를 보는 명령어
bash-5.1$ ps -au | grep psql
postgres   40821  0.0  0.0  14344  6876 pts/1    T    10:27   0:00 psql
postgres   41749  0.0  0.0   3852  2008 pts/1    S+   10:28   0:00 grep psql

현재 PostgreSQL인 psql이 postgres 유저에 의해서 실행됨을 알 수 있습니다. 만약 해커가 실행 중인 psql(PostgreSQL) 프로세스를 탈취했을 때, 해당 프로세스가 postgres 유저에 의해 실행 중이라면, 해커는 postgres의 계정만을 탈취하겠지만, 만약 해당 프로세스가 root에 의해 실행 중이라면, 해커는 root의 권한을 넘겨받게 됩니다. 리눅스의 경우, root의 권한이 굉장히 강력한 편이기 때문에, 몇몇 데이터베이스의 경우, 특정 계정 사용을 강제하는 듯 합니다.

 


 

 

아무튼 이어갑시다.

[postgres@0c6f22bdea32 ~]$ /usr/pgsql-15/bin/initdb
# 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 "C.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.

# creating directory /var/lib/pgsql/15/data ... 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

 

 

설치 경로나, 버전에 따라 다를 수는 있겠으나, 일반적으로 아래와 같은 형식이겠습니다.

[postgres로_로그인] $ /설치경로/pgsql-버전/bin/initdb

 

 

실행

initdb가 완료되었으면, 현재 서비스가 구동되고 있는지 확인을 합니다.

만약 systemctl 명령어가 없는 경우, systemd를 설치해주시면됩니다.

# 서비스 현 상태를 출력해주는 명령어
systemctl status postgresql-15

# PostgreSQL 15버전이 아닌 경우
systemctl status postgresql-<버전>

 

 

Loaded 부분을 보면 disabled 되어있네요. Active 부분도 inactive로 표시되어있습니다.

[postgres@0c6f22bdea32 ~]$ systemctl status postgresql-15
# ○ postgresql-15.service - PostgreSQL 15 database server
#      Loaded: loaded (/usr/lib/systemd/system/postgresql-15.service; disabled; preset: disabled)
#      Active: inactive (dead)
#        Docs: https://www.postgresql.org/docs/15/static/

 

 

[ Access Denied ]  postgres 계정은 서버를 실행하거나 중단할 권한이 없나봅니다.

[postgres@0c6f22bdea32 ~]$ systemctl enable postgresql-15
Failed to enable unit: Access denied

 

 

PostgreSQL에 관한 권한은 postgres에 있지만, 리눅스 운영체제에서 서비스를 동작하는 권한은 postgres에 주어지지 않았습니다(확인=status만 가능). root로 옮겨가 진행합니다.

# root로 유저 변경
[postgres@0c6f22bdea32 ~]$ su root
Password: 

# 이후 부팅시 postgresql-15가 자동 실행되게 만듬
# 바로가기와 같은 링크를 걸어서 시작프로그램 폴더에 넣는 것과 비슷합니다.
[root@0c6f22bdea32 pgsql]$ systemctl enable postgresql-15
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql-15.service → /usr/lib/systemd/system/postgresql-15.service.

# postgresql-15 서비스 실행
# enable만하면 지금 바로 실행되는건 아니고, 부팅시 실행됩니다.
[root@0c6f22bdea32 pgsql]$ systemctl start postgresql-15

+ 혹시 도커에서 root 최초 비밀번호 설정을 잊고 유저를 옮겨가신 경우, 터미널 하나를 더 여시면 보통 root로 열리기 때문에, 그 쪽에서 설정하셔도 될 것 같습니다.

 

 

다시 status를 확인해보면 아래와 같이 잘 실행되고 있음을 알 수 있습니다.

약간씩 다르기는 하겠으나, 프롬프트 상에서 초록색으로 표시되기 때문에 작동여부는 직관적인 편입니다.

[root@0c6f22bdea32 ~]# systemctl status postgresql-15
● postgresql-15.service - PostgreSQL 15 database server
     Loaded: loaded (/usr/lib/systemd/system/postgresql-15.service; enabled; preset: disabled)
     Active: active (running) since Mon 2024-04-15 10:06:50 KST; 54min ago
       Docs: https://www.postgresql.org/docs/15/static/
    Process: 26091 ExecStartPre=/usr/pgsql-15/bin/postgresql-15-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS)
   Main PID: 26096 (postmaster)
     CGroup: /docker/0c6f22bdea3227c1330644d2ab44395e391ee8504b2bb18135aaee98b1391288/system.slice/postgresql-15.service
             ├─26096 /usr/pgsql-15/bin/postmaster -D /var/lib/pgsql/15/data/
             ├─26097 "postgres: logger "
             ├─26098 "postgres: checkpointer "
             ├─26099 "postgres: background writer "
lines 1-11...skipping...

 


 

동작 테스트

[root@0c6f22bdea32 ~]# su postgres
bash-5.1$ psql
could not change directory to "/root": Permission denied
psql (15.6)
Type "help" for help.

postgres=#​

 


 

 

 

 

필요하신 분들만

PostgreSQL initdb와 관련된 옵션들:

 

initdb

initdb initdb — 새 PostgreSQL 데이터베이스 클러스터 만들기 요약 initdb [옵션...] [ --pgdata | -D ] 디렉터리 설명 initdb 명령은 PostgreSQL 데이터베이스 클러스터를 새로 만드는데 사용한다. 데이터베이스

postgresql.kr

 


 

반응형