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/
.
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
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