티스토리 뷰

WEB2.0/프로그래밍

postgresql docker 활용하기

나를찾는아이 2025. 1. 21. 17:44
728x90
반응형

https://hub.docker.com/_/postgres

 

postgres - Official Image | Docker Hub

Note: the description for this image is longer than the Hub length limit of 25000, so has been trimmed. The full description can be found at https://github.com/docker-library/docs/tree/master/postgres/README.md⁠. See also docker/hub-feedback#238⁠ and d

hub.docker.com

 

postgres를 도커를 이용하여 사용하는데 있어서 필요한 유용한 내용들을 정리해보았습니다

 

 

$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

 

 

공식 postgres 도커 이미지를 이용하여 필수 환경변수인 POSTGRES_PASWORD만 지정하면 매우 손쉽게 컨테이너 실행이 가능합니다

 

POSTGRES_PASWORD에 지정된 비밀번호를 사용하며,

 

기본값으로 사용자이름과 db명은 postgres가 사용됩니다

 

 

 

services:

  db:
    image: postgres
    restart: always
    # set shared memory limit when using docker-compose
    shm_size: 128mb
    # or set shared memory limit when deploy via swarm stack
    #volumes:
    #  - type: tmpfs
    #    target: /dev/shm
    #    tmpfs:
    #      size: 134217728 # 128*2^20 bytes = 128Mb
    environment:
      POSTGRES_PASSWORD: example

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

 

도커컴포즈를 이용하여 구성할수 있습니다

 

공식 예제에는 adminer라는 UI도구를 함께 설치하여 사용하는 예제가 있네요

 

 

# Use postgres/example user/password credentials
version: '3.9'

services:

  db:
    image: postgres
    restart: always
    # set shared memory limit when using docker-compose
    shm_size: 128mb
    # or set shared memory limit when deploy via swarm stack
    #volumes:
    #  - type: tmpfs
    #    target: /dev/shm
    #    tmpfs:
    #      size: 134217728 # 128*2^20 bytes = 128Mb
    environment:
      POSTGRES_PASSWORD: example

  pgadmin:
    image: dpage/pgadmin4
    restart: always
    environment:
        - PGADMIN_DEFAULT_EMAIL=admin@admin.com
        - PGADMIN_DEFAULT_PASSWORD=pgadmin4
    ports:
      - '5050:80'
    depends_on:
      - db

 

 

널리 알려진 pgadmin을 통해서도 위와 같이 구성할수 있습니다

 

pgadmin에서 사용가능한 환경변수는 다음과 같습니다

 

https://www.pgadmin.org/docs/pgadmin4/8.13/container_deployment.html

 

Container Deployment — pgAdmin 4 8.13 documentation

There are various tags that you can select from to get the version of pgAdmin that you want, using a command such as this if you’re using Docker: PostgreSQL Utilities The PostgreSQL utilities pg_dump, pg_dumpall, pg_restore and psql are included in the c

www.pgadmin.org

 

 

유용한 팁을 하나 더 드리자면

 

 

  pgadmin:
    image: dpage/pgadmin4
    restart: always
    volumes:
      - ./pgadmin4/servers.json:/pgadmin4/servers.json

 

 

/pgadmin4/servers.json 파일로 다음과 같은 파일을 마운트하면

 

// servers.json
{
  "Servers": {
    "1": {
      "Name": "postgres",
      "Group": "Servers",
      "Port": 5432,
      "Username": "postgres",
      "Host": "postgres",
      "SSLMode": "prefer",
      "MaintenanceDB": "postgres"
    }
  }
}

 

 

servers.json 파일을 읽어 기본 커넥션에 등록을 해둡니다

 

매번 커넥션을 등록하지 않아도 됩니다

 

다만 비밀번호는 UI상에서 저장을 해야합니다

 

 

 

 

 

postgres 에 가장 흔히 사용되는 환경변수는 다음과 같습니다

 

 

POSTGRES_PASSWORD : 비밀번호(필수)

POSTGRES_USER : 유저명(없으면 postgres 가 기본값)

POSTGRES_DB : 디비명(없으면 POSTGRES_USER에서 지정한 값이 사용됨)

 

 

DB를 세팅했으니, 초기 스키마를 생성하고, 필요한 데이터를 넣는 작업이 필요할수 있습니다

 

# seed.sql
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50),
  email VARCHAR(100) UNIQUE
);

INSERT INTO users (name, email) VALUES
  ('Alpha', 'alpha@example.com'),
  ('Beta', 'beta@example.com'),
  ('Gamma', 'gamma@example.com');

 

 

이 과정은 여러가지 방법을 이용할 수 있습니다

 

psql 명령어를 사용하여 실행할 수 있고, 직접 js 파일을 만들어 코드를 통해 주입해도 됩니다

 

 

저는 좀더 우아한 방법이라고 생각하는 마운트를 이용한 방법을 추천합니다

 

postgres 도커이미지는 /docker-entrypoint-initdb.d 해당 경로의 sh 파일 및 sql 파일을 컨테이너 생성 후에 실행합니다

 

그러니 원하는 작업이 있다면 해당 경로로 파일을 COPY를 한다면 손쉽게 sql 파일을 실행시킬수 있습니다

 

# syntax=docker/dockerfile:1
FROM postgres:latest
COPY seed.sql /docker-entrypoint-initdb.d/

 

이렇게 말이죠

 

 

컨테이너가 중지되어도 데이터를 잃지 않으려면 volumes을 구성합니다

 

services:
  db:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: my_postgres_db
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: sampledb
    ports:
      - "5432:5432"
    volumes:
      - data_sql:/var/lib/postgresql/data   # Persistent data storage

volumes:
  data_sql:

 

 

volumes 설정을 통해 컨테이너가 중지되더라도 데이터는 그대로 보존할수 있습니다

 

이 볼륨도 삭제를 원하다면 down 명령어 실행시 -v 옵션을 통해 볼륨까지 삭제가 가능합니다

 

 

 

위의 도커컴포즈 환경을 실행해봅시다

 

docker compose up -d --build

 

 

 

명령어 차이는 없습니다

 

 

 

postgres 컨테이너의 생성이 바로 healthy를 의미하는것은 아닙니다

 

진정한 healthcheck를 위해 pg_isready 명령어를 사용할수 있습니다

 

services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
        restart: true
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      retries: 5
      start_period: 30s
      timeout: 10s

 

healthcheck를 통해 원하는 healthcheck 방법 및 옵션을 설정할수 있으며,

 

이는 compose 내에서 depens_on 옵션을 통해 의존관계와 더불어 의존관계의 condition까지 추가 체크할수 있습니다

 

 

 

condition 값은 다음과 같습니다

 

service_started : (기본값)서비스가 시작됨

service_healthy : healthcheck가 성공함

service_completed_successfully : 서비스가 성공적으로 완료됨

 

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함