Add central postgres database

This commit is contained in:
2026-04-01 18:53:41 +02:00
parent 7687069827
commit 7aaeffddde
3 changed files with 79 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
services:
db:
image: postgres@sha256:035b9ab53cfa147d7202b61f5f7782b939ae815b7d6bc81c96b7b42ff1fca950
container_name: postgres
restart: unless-stopped
entrypoint: ["/bin/bash", "/init/entrypoint.sh"]
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
volumes:
- postgres_data:/var/lib/postgresql
- ./init:/init:ro
networks:
- homelab_db
secrets:
- postgres_password
- authentik_postgres_password
- gitea_postgres_password
healthcheck:
interval: 30s
retries: 5
start_period: 20s
test:
- CMD-SHELL
- pg_isready -U postgres
timeout: 5s
volumes:
postgres_data:
driver: local
networks:
homelab_db:
name: homelab_db
secrets:
postgres_password:
environment: POSTGRES_PASSWORD
authentik_postgres_password:
environment: AUTHENTIK_POSTGRES_PASSWORD
gitea_postgres_password:
environment: GITEA_POSTGRES_PASSWORD

View File

@@ -0,0 +1,31 @@
#!/bin/bash
set -euo pipefail
until pg_isready -U "$POSTGRES_USER" -q; do sleep 1; done
for secret_file in /run/secrets/*_postgres_password; do
[ -f "$secret_file" ] || continue
[ "$secret_file" = "/run/secrets/postgres_password" ] && continue
service="$(basename "$secret_file" _postgres_password)"
password="$(cat "$secret_file")"
echo "Ensuring database and user for '$service'..."
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-SQL
DO \$\$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '$service') THEN
CREATE ROLE "$service" WITH LOGIN PASSWORD '$password';
ELSE
ALTER ROLE "$service" WITH PASSWORD '$password';
END IF;
END
\$\$;
SELECT 'CREATE DATABASE "$service" OWNER "$service"'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$service')\gexec
SQL
done
touch /tmp/init_complete

View File

@@ -0,0 +1,6 @@
#!/bin/bash
set -euo pipefail
/init/create-service-dbs.sh &
exec docker-entrypoint.sh postgres