docker-compose.yml如下:
version: '3'services:postgres:image: postgres:15.4healthcheck:test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "root" ]timeout: 45sinterval: 10sretries: 10restart: alwaysenvironment:- POSTGRES_USER=root- POSTGRES_PASSWORD=123456- APP_DB_USER=user01- APP_DB_PASS=123456- APP_DB_NAME=my_appvolumes:- ./db:/docker-entrypoint-initdb.d/- /data/postgres:/var/lib/postgresql/dataports:- 5432:5432
db\01-init.sh如下
#!/bin/bash
set -e
export PGPASSWORD=$POSTGRES_PASSWORD;
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQLCREATE USER $APP_DB_USER WITH PASSWORD '$APP_DB_PASS';CREATE DATABASE $APP_DB_NAME;GRANT ALL PRIVILEGES ON DATABASE $APP_DB_NAME TO $APP_DB_USER;\connect $APP_DB_NAME $APP_DB_USERBEGIN;CREATE TABLE IF NOT EXISTS event (id CHAR(26) NOT NULL CHECK (CHAR_LENGTH(id) = 26) PRIMARY KEY,aggregate_id CHAR(26) NOT NULL CHECK (CHAR_LENGTH(aggregate_id) = 26),event_data JSON NOT NULL,version INT,UNIQUE(aggregate_id, version));CREATE INDEX idx_event_aggregate_id ON event (aggregate_id);COMMIT;
EOSQL