Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active April 13, 2025 20:03
Show Gist options
  • Save drmalex07/378532adf24df488e4c7dcd1fe94b5f7 to your computer and use it in GitHub Desktop.
Save drmalex07/378532adf24df488e4c7dcd1fe94b5f7 to your computer and use it in GitHub Desktop.
An example docker-compose recipe. #docker-compose #postgresql

Readme - An example PostgreSQL docker-compose recipe

Prepare init script under /db-init-scripts/. For example, create db-init-scripts/s01-create-test1-database.sh:

#!bin/bash
set -e -u -o pipefail

quote='$q$'
pass=$(cat /secrets/tester1-password)

psql -v ON_ERROR_STOP=1 -U "${POSTGRES_USER}" -d "${POSTGRES_DB}" <<-EOD
CREATE USER tester1 WITH PASSWORD ${quote}${pass}${quote} LOGIN;
CREATE DATABASE test1 OWNER tester1;
EOD

Prepare secrets under secrets/.

1. For docker-compose

The compose recipe:

volumes:
  postgres_data:

services:

  postgres:
    image: postgres:10.14-alpine
    volumes:
    - type: volume
      source: postgres_data
      target: /var/lib/postgresql/data
    - type: bind
      source: ./db-init-scripts/
      target: /docker-entrypoint-initdb.d/
      read_only: true
    - type: bind
      source: ./secrets/
      target: /secrets/
      read_only: true
    environment:
      POSTGRES_PASSWORD_FILE: /secrets/postgres-password

2. For docker-stack (deploy in swarm mode)

The compose recipe:

configs:
  init_sql:
    file: ./db-init-scripts/s01-create-test1-database.sh

secrets:
  postgres_password:
    file: ./secrets/postgres-password

volumes:
  postgres_data:

services:

  postgres:
    image: postgres:15-alpine
    secrets:
    - source: postgres_password
      target: /secrets/postgres-password
    configs:
    - source: init_sql
      target: /docker-entrypoint-initdb.d/schema.sql
    volumes:
    - type: volume
      source: postgres_data
      target: /var/lib/postgresql/data  
    environment:
      POSTGRES_PASSWORD_FILE: /secrets/postgres-password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment