Add central postgres database
This commit is contained in:
42
stacks/postgres/docker-compose.yaml
Normal file
42
stacks/postgres/docker-compose.yaml
Normal 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
|
||||
31
stacks/postgres/init/create-service-dbs.sh
Executable file
31
stacks/postgres/init/create-service-dbs.sh
Executable 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
|
||||
6
stacks/postgres/init/entrypoint.sh
Executable file
6
stacks/postgres/init/entrypoint.sh
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
/init/create-service-dbs.sh &
|
||||
|
||||
exec docker-entrypoint.sh postgres
|
||||
Reference in New Issue
Block a user