Django에 Docker를 이용한 PostgreSQL을 연동해보자

cloud_park·2023년 9월 18일
0

postgreSQL 비밀번호 환경변수 셋팅

export POSTGRES_PASSWORD='my_password'
echo $POSTGRES_PASSWORD

/var/lib/postgresql/data (Local 머신의 Postgresql 저장소) 생성

Docker 배포

#! /bin/bash

docker run -d -p 5432:5432 \
    --name postgres \
    --restart=always \
    -v /var/lib/postgresql/data:/var/lib/postgresql/data \
    -e POSTGRES_PASSWORD=$POSTGRES_PASSWORD \
     postgres

Postgres 접속

docker exec --it postgres bash

psql 접속

psql -U postgres

DATABASE 생성

CREATE DATABASE [my_service];

\l 을 통해 my_service 생성을 확인할 수 있다.

USER 생성 및 권한부여

CREATE USER [my_user_name] WITH PASSWORD 'password'; 
-- 해당 'password'부분은 따옴표로 감싸져있어야한다. 
ALTER ROLE [my_user_name] set client_encoding to 'utf-8';
ALTER ROLE [my_user_name] set timezone to 'Asia/Seoul';
ALTER ROLE [my_user_name] SET default_transaction_isolation TO 'read committed'
grant all privileges on database [my_service] to [my_user_name];

--Postgresql 15부터 public schema에 대한 권한도 줘야하며, DB의 owner가 되어야한다. 
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO [my_user_name];
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO [my_user_name];

setttings.py 셋팅

settings.py
import os
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': [my_service],
        'USER': [my_user_name],
        'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
        'HOST' : `localhost`,
        'PORT' : '5432',
    }
}

postgresql 드라이버 설치

pip install psycopg2

permission denied for schema public 해결

python3 manage.py migrate

django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (permission denied for schema public
LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR...

https://stackoverflow.com/questions/74110708/postgres-15-permission-denied-for-schema-public

이유는 DB의 모든 권한은 주었다고 하더라도, DB의 'Owner'가 되어야 CREATE를 할 수 있게 변경되었다고 한다. 따라서 DB의 주인을 바꿔준다.

ALTER DATABASE [my_service] OWNER TO [my_user];

잘 된다. 오예.

profile
Now in progress of untitled advance

0개의 댓글