Lab 3: HAProxy + 2 replicas, idempotency, graceful shutdown, track 1

This commit is contained in:
2026-11-16 21:48:11 +03:00
parent 0ab3a341aa
commit a3ac20d017
107 changed files with 24088 additions and 15 deletions
+172
View File
@@ -0,0 +1,172 @@
# Учебный стенд lab3: HAProxy (единственная точка входа) → API × N → PostgreSQL + Redis.
# Запуск: ./scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait
name: mtusi-lab3
x-api-common: &api-common
build:
context: .
dockerfile: Dockerfile
image: mtusi-lab3-api:local
environment: &api-env
APP_HOST: 0.0.0.0
APP_PORT: "8080"
APP_ENV: ${APP_ENV:-lab}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_STORE: postgres
SESSION_CACHE: ${SESSION_CACHE:-redis}
SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
DATABASE_URL_FILE: /run/secrets/database_url
CACHE_URL_FILE: /run/secrets/cache_url
DB_POOL_MIN: "1"
DB_POOL_MAX: ${DB_POOL_MAX:-10}
DB_POOL_TIMEOUT_SECONDS: "2"
KDF_CONCURRENCY: ${KDF_CONCURRENCY:-4} # каждый scrypt ≈ 32 MiB RAM: учитывайте в API_MEMORY
DB_STATEMENT_TIMEOUT_MS: "5000"
CACHE_TIMEOUT_SECONDS: "0.2"
REQUEST_TIMEOUT_SECONDS: "10"
SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3}
MIGRATE_ON_START: "false" # миграции — только сервис migrate
secrets: [database_url, cache_url]
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_started # Redis — кэш: реплики работают и без него
networks: [app, data] # НЕТ ports: API доступен только через LB
read_only: true
tmpfs: [/tmp]
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
restart: unless-stopped
stop_signal: SIGTERM
stop_grace_period: 15s # drain 3 с + завершение запросов в полёте (≤10 с)
services:
lb:
image: haproxy:3.0.5-alpine
volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
environment:
LB_SERVER_MAXCONN: ${LB_SERVER_MAXCONN:-10}
LB_QUEUE_TIMEOUT: ${LB_QUEUE_TIMEOUT:-2s}
ports:
- "127.0.0.1:${API_PORT:-8080}:8080" # публичный API
- "127.0.0.1:${API_TTL_PORT:-8081}:8081" # api-ttl (профиль ttl), тоже только через LB
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # статистика HAProxy (только чтение)
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/stats"]
interval: 5s
timeout: 2s
retries: 3
networks: [edge, app]
restart: unless-stopped
stop_grace_period: 5s
deploy:
resources:
limits: {cpus: "0.5", memory: 128M}
# One-shot: миграции применяются ОДИН раз до запуска реплик (не гонкой реплик).
# Повторный запуск (docker compose run --rm migrate) — no-op. Реплики не становятся ready,
# пока схема не содержит все известные им миграции.
migrate:
<<: *api-common
command: ["migrate"]
depends_on:
postgres:
condition: service_healthy
networks: [data]
restart: "no"
secrets: [database_url]
environment:
<<: *api-env
SESSION_CACHE: "off"
deploy:
resources:
limits: {cpus: "0.5", memory: 256M}
api:
<<: *api-common
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512M}"}
# Экземпляр с коротким TTL — только для теста истечения; доступен через LB на :8081.
api-ttl:
<<: *api-common
profiles: [ttl]
environment:
<<: *api-env
SESSION_TTL_SECONDS: "2"
deploy:
resources:
limits: {cpus: "0.5", memory: 256M}
postgres:
image: postgres:16.10-alpine
environment:
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256 --data-checksums"
command: ["postgres", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"]
secrets: [postgres_password]
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -h 127.0.0.1"]
interval: 2s
timeout: 3s
retries: 30
start_period: 10s
networks: [data]
shm_size: 256m
restart: unless-stopped
stop_grace_period: 30s
deploy:
resources:
limits: {cpus: "${PG_CPUS:-1.0}", memory: 1G}
# Redis — общий кэш сессий без persistence; источник истины сессий — PostgreSQL.
redis:
image: redis:7.4.2-alpine
command:
- sh
- -c
- |
umask 077
printf 'requirepass %s\n' "$$(cat /run/secrets/redis_password)" > /tmp/redis.conf
exec redis-server /tmp/redis.conf --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru
user: redis
secrets: [redis_password]
healthcheck:
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_password)\" redis-cli ping | grep -q PONG"]
interval: 2s
timeout: 2s
retries: 15
networks: [data]
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
networks:
edge: {} # только LB: публикация портов на 127.0.0.1
app:
internal: true # LB ↔ API
data:
internal: true # API ↔ PostgreSQL/Redis
volumes:
pgdata: {}
secrets:
postgres_password:
file: ./secrets/postgres_password
redis_password:
file: ./secrets/redis_password
database_url:
file: ./secrets/database_url
cache_url:
file: ./secrets/cache_url