반응형
Django에서는 공식적으로 PostgreSQL DB를 사용할 것을 강력히 추천하고 있다. 내가 써봐도 PostgreSQL이 제일 좋은 것 같다. 오늘은 PostgreSQL을 설치하고, Django settings에 설정해서 연결하는 방법을 총정리 해보도록 하겠다.
1. PostgreSQL 설치
공식적으로 PostgreSQL은 ubuntu 18.04, 20.04, 22.04 LTS 버젼을 지원하고 있다. 이 의미는 apt-get으로 손쉽게 설치할 수 있다는 얘기가 된다.
- postgresql-12 우분투 설치: 모든 자료들이 12버젼을 기준으로 설명하고 있기 때문에 가장 안정된 버전으로 생각해도 좋을 것 같다. 설치중에 Yes를 누르면 관련 패키지들까지 알아서 잘 설치를 해준다.
sudo apt-get install postgresql-12
--------------------------------------
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libllvm10 libpq5 libsensors-config libsensors5 postgresql-client-12 postgresql-client-common postgresql-common
ssl-cert sysstat
Suggested packages:
lm-sensors postgresql-doc-12 libjson-perl openssl-blacklist isag
The following NEW packages will be installed:
libllvm10 libpq5 libsensors-config libsensors5 postgresql-12 postgresql-client-12 postgresql-client-common
postgresql-common ssl-cert sysstat
0 upgraded, 10 newly installed, 0 to remove and 104 not upgraded.
Need to get 30.7 MB of archives.
After this operation, 122 MB of additional disk space will be used.
Do you want to continue? [Y/n]
- 설치 성공 후 메세지 저장: 설치가 성공적으로 완료가 되면 아래와 같은 메세지가 나오는데 개발하면서 필요한 정보이니 꼭 메모해 두기 바란다. 대략 의미는 DB는 /var/lib/postgresql/12/main에 설치되어 있고 관리자 사용자명은 postgres, 포트는 5432, 현재상태는 down, 로그는 /var/log/postgresql에서 볼 수 있다라는 것이다.
Success. You can now start the database server using:
pg_ctlcluster 12 main start
Ver Cluster Port Status Owner Data directory Log file
12 main 5432 down postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log
- PostgreSQL 데몬 서비스 시작: 위의 정보와 같이 현재 멈춰있는 상태이니 시작 명령을 준다.
sudo systemctl start postgresql

- 서비스가 정상적이더라도 실제 postgresql에 접속이 잘 되는지도 확인해본다. 위의 정보에서 알려주었던 Owner인 postgres라는 사용자명으로 접속해보겠다. 로그인 상태를 간단히 확인하는 과정이다. 참고로, 비밀번호를 물어보지 않으니 걱정하지 않아도 된다.
sudo -i -u postgres
psql
postgres-# \conninfo
You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".
postgres-# \q
2. PostgreSQL 신규 계정 및 데이터베이스 생성
- 신규 계정 생성: 현재 postgres 계정으로 접속되어 있는 상태에서 createuser 명령을 실행한다. 계정이름은 Amazon Lightsail에서 사용하는 이름과 똑같이 만들어두면 나중에 여러모로 편리해지니 이 이름을 권장한다. 지금 단계에서는 비밀번호를 물어보지 않는다.
postgres@server:~$ createuser --interactive
Enter name of role to add: dbmasteruser
Shall the new role be a superuser? (y/n) y
- 비밀번호 설정: 외부 IP에서 접속하기 위해서는 패스워드를 설정해주어야 한다.
sudo -i -u postgres (새로 만든 계정이 아닌 admin 기본 계정으로 접속)
psql
postgres=# alter user dbmasteruser with password 'xxxxxxxxx';
ALTER ROLE (성공했다는 의미임)
- 이제 다시 dbmasteruser 계정으로 PostgreSQL에 접속해서 접속 정보를 확인하면서 정상적으로 잘 수행이 되었는지 검증해본다. 이때 기본적으로 psql은 계정이름과 똑같은 db 이름을 찾기 때문에 -d 옵션을 주어 기존 db 이름으로 접속되도록 하여야 한다.
sudo -i -u dbmasteruser
psql -d postgres (디폴트 DB 이름)
psql (12.14 (Ubuntu 12.14-0ubuntu0.20.04.1))
Type "help" for help.
postgres=#
postgres=# \conninfo
You are connected to database "postgres" as user "dbmasteruser" via socket in "/var/run/postgresql" at port "5432".
모든게 다 정상적으로 설치가 완료되었다.
3. Django Settings 외부 연결 설정
- postgresql.conf 파일 수정: 모든 외부 IP에서 접속할 수 있도록 listen_addresses = '0.0.0.0' 를 추가해준다.
sudo vi /etc/postgresql/12/main/postgresql.conf
--------------------------------------
...
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------
# - Connection Settings -
#listen_addresses = 'localhost' # what IP address(es) to listen on;
listen_addresses = '0.0.0.0' # 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)
...
- pg_hba.conf 수정: IPv4에서 모두 접속가능하도록 0.0.0.0/0 으로 수정해준다.
sudo vi /etc/postgresql/12/main/pg_hba.conf
--------------------------
...
# IPv4 local connections:
#host all all 127.0.0.1/32 md5
host all all 0.0.0.0/0 md5
...
- 데몬 서비스 재시작
sudo systemctl restart postgresql
- Django에서는 기본 DB인 SqlLite 설정을 주석처리하고 PostgreSQL로 대체한다.
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'dbmasteruser',
'PASSWORD': 'xxxxxxxx',
'HOST': '1.2.3.4',
'PORT': 5432,
}
}
4. PostgreSQL Client 윈도우용 pgAdmin 4 설치
- DB 관리를 위해서 윈도우 클라이언트가 있으면 매우 편리하기 때문에 가장 많이 쓰는 pgAdmin을 다운로드 받아서 설치한다.


이제, 클라이언트에서 위에서 설정하였던 정보로 접속을 하면 모든 설정이 완료된다.
반응형
'Django' 카테고리의 다른 글
Django Model 다양한 관계 설정 (0) | 2023.04.23 |
---|---|
Django search request 처리하는 방법 (0) | 2023.04.09 |
Django templates static 디렉토리 설정 방법 (0) | 2023.04.08 |
Django 평생 무료로 https 서버 설정하는 방법 (0) | 2023.04.07 |
Django http 도메인 주소로 설정하는 방법 총정리 (0) | 2023.04.07 |
댓글