Добавить Dockerfile и Compose-стенд с secrets и именованным volume

This commit is contained in:
2026-11-16 21:47:35 +00:00
parent d876930498
commit d7a30a6c4a
3 changed files with 78 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.11.11-slim-bookworm
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY messenger ./messenger
EXPOSE 8080
COPY migrations ./migrations
COPY scripts/start.sh ./scripts/start.sh
CMD ["sh", "scripts/start.sh"]
+44
View File
@@ -0,0 +1,44 @@
services:
db:
image: postgres:16.6-bookworm
environment:
POSTGRES_DB: messenger
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 2s
timeout: 3s
retries: 30
api:
build: .
environment:
APP_HOST: ${APP_HOST:-0.0.0.0}
APP_PORT: ${APP_PORT:-8080}
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_STORE: postgres
DATABASE_URL_FILE: /run/secrets/database_url
ports:
- "127.0.0.1:8080:${APP_PORT:-8080}"
secrets:
- database_url
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:'+os.getenv('APP_PORT','8080')+'/health/ready',timeout=3)"]
interval: 3s
timeout: 5s
retries: 20
volumes:
postgres_data:
secrets:
postgres_password:
file: ./secrets/postgres_password
database_url:
file: ./secrets/database_url
+24
View File
@@ -0,0 +1,24 @@
"""Create local secrets once. Never overwrite existing credentials."""
from pathlib import Path
import secrets
import shutil
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(mode=0o700, exist_ok=True)
password_file = directory / 'postgres_password'
url_file = directory / 'database_url'
if password_file.exists() != url_file.exists():
raise SystemExit('Incomplete secrets: restore the missing file; do not regenerate credentials for an existing volume.')
if not password_file.exists():
password = secrets.token_hex(32)
for path, value in [(password_file, password),
(url_file, 'postgresql://messenger:' + password + '@db:5432/messenger')]:
with path.open('x', encoding='utf-8') as f:
f.write(value + '\n')
# Compose mounts secret files individually; PostgreSQL runs as a distinct UID.
# The enclosing host directory is 0700, while this mounted file must be readable.
path.chmod(0o644 if path == password_file else 0o600)
if not (root / '.env').exists():
shutil.copyfile(root / '.env.example', root / '.env')
print('Local configuration ready; existing credentials preserved.')