-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-compose.yml
More file actions
536 lines (525 loc) · 27.3 KB
/
Copy pathdocker-compose.yml
File metadata and controls
536 lines (525 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# vibe-order-infra
#
# Учебная инфраструктура сайта приёма и обработки клиентских заявок.
# Compose Specification (без устаревшего поля "version").
#
# ВАЖНО: этот файл предназначен для запуска на Ubuntu 24.04 VPS,
# где UFW открыт только на 22/80/443. Сам файл здесь не запускается.
#
# Все обязательные переменные окружения используют форму ${VAR:?...} —
# `docker compose config`/`up` откажется стартовать без .env с реальными
# значениями вместо того, чтобы молча подставить пустую строку.
services:
# ------------------------------------------------------------------
# PostgreSQL — база данных заявок.
# Порт 5432 НЕ публикуется на host: доступ только изнутри app-net
# (pgAdmin и backend обращаются к сервису по имени "postgres").
# ------------------------------------------------------------------
postgres:
# Stage 3: закреплён и по точной версии, и по immutable digest — это
# digest манифест-листа (image index), а не одного per-platform
# манифеста (проверено `docker buildx imagetools inspect`), поэтому
# мультиплатформенность не ломается — `docker pull`/`build` по этому
# digest продолжает резолвиться в правильный образ под текущую
# архитектуру. Тег рядом с digest — для человека; digest гарантирует,
# что под этим тегом впоследствии не подменят содержимое молча.
# Патч-апдейт 16.14 -> 16.15 (актуальный security patch level на момент
# проверки) — digest переверифицирован тем же `docker buildx imagetools
# inspect` перед обновлением этой строки.
image: postgres:16.15-alpine@sha256:cf78e76683b9ca8c5733cbbdce6c9262b45b6767934dd0a95e671f9a0fc20685
restart: unless-stopped
# Stage 4: `no-new-privileges` blocks a process from gaining more
# privileges than it started with (e.g. via a setuid/setgid binary) -
# this image's entrypoint never needs that, so it's a no-downside
# hardening flag. Deeper hardening (cap_drop, read_only) is NOT applied
# here: the official postgres entrypoint runs its first-time init
# (initdb, chown of the data directory to the postgres user) as root
# before dropping to the postgres user for the server process itself -
# cap_drop: ALL would remove CAP_CHOWN/CAP_FOWNER that step needs, and
# read_only would need tmpfs mounts for /var/run/postgresql (the unix
# socket) and more, verified live before trusting it. Deferred - see
# the Stage 4 report's "Deferred findings".
security_opt:
- no-new-privileges:true
environment:
POSTGRES_USER: "${POSTGRES_USER:?POSTGRES_USER must be set}"
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set}"
POSTGRES_DB: "${POSTGRES_DB:?POSTGRES_DB must be set}"
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- app-net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:?POSTGRES_USER must be set} -d ${POSTGRES_DB:?POSTGRES_DB must be set}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
# Ресурсы: PostgreSQL получает самую большую долю из ~1GB VPS
# намеренно — агрессивное ограничение СУБД без обоснования может
# приводить к OOM-убийству под нагрузкой (см. README, раздел
# "Resource protection").
deploy:
resources:
limits:
cpus: "1.00"
memory: 384M
reservations:
memory: 192M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# ------------------------------------------------------------------
# pgAdmin — веб-интерфейс администрирования PostgreSQL.
# Не публикуется в интернет: порт привязан только к 127.0.0.1,
# доступ с локального компьютера — через SSH-туннель. Опционален
# (профиль "admin"), чтобы не расходовать RAM на VPS с ~1GB постоянно.
#
# docker compose --profile admin up -d pgadmin
# ssh -L 5050:127.0.0.1:5050 <user>@<vps-host>
# -> открыть http://127.0.0.1:5050 в браузере на локальной машине
# ------------------------------------------------------------------
pgadmin:
# Stage 3: закреплён по версии и immutable manifest-list digest — см.
# комментарий у "postgres" выше про мультиплатформенность.
image: dpage/pgadmin4:9.16@sha256:40fa840c5bb7c8463957f1255b01283732c2d8c9396a956d180f8e6c296753b3
restart: unless-stopped
profiles:
- admin
# Stage 4: `no-new-privileges` was tried here (live, via `docker compose
# --profile admin up`) and reverted - pgAdmin's own entrypoint detects a
# "restricted security context" under it and silently switches its
# internal listen port from 80 to 8080 ("Restricted security context
# detected; defaulting PGADMIN_LISTEN_PORT to 8080" in its own logs),
# which breaks the fixed `127.0.0.1:5050:80` port mapping below (and the
# documented SSH-tunnel access flow - see this service's header comment)
# with no reachable service on the other end. Exactly the "breaks normal
# operation" case the Stage 4 spec says to revert rather than force
# through with a workaround (e.g. changing the port mapping to 8080
# would work, but is a bigger, less obviously-safe change than this
# stage's "low risk only" hardening scope justifies for an admin-only,
# loopback-only, profile-gated tool). Deferred - see the Stage 4
# report's "Deferred findings".
environment:
PGADMIN_DEFAULT_EMAIL: "${PGADMIN_DEFAULT_EMAIL:?PGADMIN_DEFAULT_EMAIL must be set}"
PGADMIN_DEFAULT_PASSWORD: "${PGADMIN_DEFAULT_PASSWORD:?PGADMIN_DEFAULT_PASSWORD must be set}"
volumes:
- pgadmin-data:/var/lib/pgadmin
ports:
# Только loopback! Публикация на 0.0.0.0 обходила бы UFW.
- "127.0.0.1:5050:80"
networks:
- app-net
depends_on:
postgres:
condition: service_healthy
deploy:
resources:
limits:
cpus: "0.50"
memory: 256M
reservations:
memory: 128M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# ------------------------------------------------------------------
# Docker Registry — приватный реестр образов.
# Порт 5000 НЕ публикуется на host. Доступен Nginx внутри proxy-net.
# Внешний доступ — только через Nginx по HTTPS
# (registry-vibe.elivcloud.org, см. nginx/conf.d). Basic Auth обеспечивается самим
# Registry через htpasswd. Registry НЕ считается готовым к запуску,
# пока registry/auth/htpasswd не создан через registry/create-user.sh
# (см. README, "Порядок первого деплоя") — без него контейнер
# стартует, но ни один запрос не пройдёт аутентификацию.
# ------------------------------------------------------------------
# Совместимость с registry:3.1.1 (CNCF distribution) проверена по
# официальной документации перед апгрейдом с registry:2.x:
# - REGISTRY_AUTH / REGISTRY_AUTH_HTPASSWD_REALM / REGISTRY_AUTH_HTPASSWD_PATH
# — конвенция REGISTRY_<SECTION>_<KEY> и bcrypt-only htpasswd не изменились;
# - default storage path /var/lib/registry не изменился;
# - default config.yml переехал на /etc/distribution/config.yml, но
# мы его не монтируем (только env var overrides), поэтому это не влияет;
# - CLI-утилита htpasswd убрана ИЗ ОБРАЗА registry — не проблема:
# registry/create-user.sh использует htpasswd с хоста (apache2-utils),
# а не `docker run --entrypoint htpasswd registry ...`.
registry:
# Stage 3: закреплён по версии и immutable manifest-list digest — см.
# комментарий у "postgres" выше про мультиплатформенность.
image: registry:3.1.1@sha256:1be55279f18a2fe1a74edf2664cac61c1bea305b7b4642dab412e7affdcb3e33
restart: unless-stopped
# Stage 4: see postgres's security_opt comment above for the same
# rationale - this flag alone is unconditionally safe; cap_drop/
# read_only are deferred without a live compatibility proof for this
# image specifically (untested whether its own runtime user can write
# /var/lib/registry - the named volume - under a read-only root fs).
security_opt:
- no-new-privileges:true
environment:
REGISTRY_AUTH: htpasswd
REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
volumes:
- registry-data:/var/lib/registry
- ./registry/auth:/auth:ro
networks:
- proxy-net
# Здоровье не проверяем автоматически: с включённым htpasswd-auth
# "/v2/" без креденшлов отвечает 401, что дало бы ложное "unhealthy",
# а отдельного анонимного health-эндпоинта у образа registry нет.
deploy:
resources:
limits:
cpus: "0.50"
memory: 192M
reservations:
memory: 64M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# ------------------------------------------------------------------
# Nginx — единственный публичный сервис (80/443).
# HTTPS-блоки для vibe.elivcloud.org и registry-vibe.elivcloud.org
# активны в конфигурации (сертификат Let's Encrypt выпущен на VPS и
# монтируется из /etc/letsencrypt, см. volumes ниже) и подтверждены
# реальным serverside smoke-test'ом на публичном домене (см. README,
# "Production smoke checklist" и "Ручная end-to-end приемка"). HTTP (80)
# отдаёт ACME challenge и редиректит остальной трафик на HTTPS для обоих
# доменов. Registry проксируется только по HTTPS. Backend на 443
# проксируется через allowlist `/api/*` (см. nginx/conf.d), статика
# `frontend/dist` отдаётся тем же server{} блоком с SPA fallback.
# ------------------------------------------------------------------
nginx:
# Stage 3: закреплён по версии и immutable manifest-list digest — см.
# комментарий у "postgres" выше про мультиплатформенность.
image: nginx:1.30.4-alpine@sha256:dc5069ad14f19660b141b21236140b91656bf89bbc3e2417c70ae650cd66104c
restart: unless-stopped
security_opt:
- no-new-privileges:true
# Stage 4: cap_drop ALL + a minimal explicit cap_add, proven live (see
# the Stage 4 report) - the official nginx image's master process starts
# as root only to bind ports 80/443 (NET_BIND_SERVICE) and to setuid/
# setgid its worker processes down to the "nginx" user (SETUID/SETGID);
# CHOWN covers the entrypoint's ownership fix-up of its own writable
# runtime directories below. Everything else this image does is
# ordinary unprivileged work.
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
- SETUID
- SETGID
- CHOWN
# read_only root filesystem, proven live: every actual write nginx does
# at runtime is confined to a short, fixed list of paths, all now
# tmpfs - access/error logs are symlinked to /dev/stdout,/dev/stderr by
# this image already (no log directory writes needed), so only the
# proxy/client-body buffering cache dirs, the pid file and /tmp (the
# entrypoint's own scratch space) need to be writable.
read_only: true
tmpfs:
- /var/cache/nginx
- /var/run
- /tmp
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./nginx/acme-challenge:/var/www/acme-challenge:ro
- ./nginx/certs:/etc/nginx/certs:ro
# Реальные TLS-сертификаты Let's Encrypt — читаем напрямую с VPS,
# НЕ копируем в репозиторий и НЕ кладём в ./nginx/certs (см. README).
# Один сертификат покрывает vibe.elivcloud.org и
# registry-vibe.elivcloud.org (SAN), физически лежит только под
# /etc/letsencrypt/live/vibe.elivcloud.org/ на хосте.
- /etc/letsencrypt:/etc/letsencrypt:ro
# Собранный статический frontend (Vite build, см. frontend/README) —
# read-only bind mount готового frontend/dist прямо в стандартный
# webroot образа nginx. Собирается ВНЕ этого контейнера (временным
# Node-контейнером на хосте), сам nginx Node/npm не содержит.
- ./frontend/dist:/usr/share/nginx/html:ro
networks:
- proxy-net
depends_on:
registry:
condition: service_started
# Stage 3: backend теперь имеет реальный healthcheck (см. сервис
# "backend" ниже и backend/Dockerfile) — condition: service_healthy
# заставляет Compose держать Nginx на старте, пока backend не
# пройдёт свой healthcheck (readiness через /api/ready), а не просто
# "создан/запущен". Раньше (без healthcheck у backend) использовалась
# простая форма без condition, что не защищало от гонки: nginx.conf
# ссылается на upstream "backend" в location ^~ /api/ (proxy_pass
# http://backend:8000; без переменной, т.е. хост резолвится статически
# при старте/reload), в nginx.conf нет глобального "resolver" — если
# backend-контейнер ещё не готов принимать соединения в момент старта
# Nginx (холодный старт всего стека / ребут VPS), Nginx мог упасть с
# "host not found in upstream" или начать проксировать на ещё не
# готовый backend. condition: service_healthy устраняет эту гонку.
backend:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--quiet", "--spider", "http://127.0.0.1:80/healthz"]
interval: 15s
timeout: 5s
retries: 3
start_period: 5s
deploy:
resources:
limits:
cpus: "0.50"
memory: 96M
reservations:
memory: 32M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# ------------------------------------------------------------------
# Stage 2 (database lifecycle): три one-shot сервиса устанавливают роли и
# применяют Alembic-миграции ДО запуска backend. Все три используют один и
# тот же образ backend (см. backend/Dockerfile, секция про four launches
# этого образа) — отличаются только "command:" и тем, какой креденшл им
# передан через "environment:". Ни один не публикует портов, ни один не
# перезапускается ("restart" не задан = "no", запустился/отработал/вышел).
#
# Цепочка: postgres (healthy) -> db-roles-bootstrap (создаёт роли,
# выставляет ALTER DEFAULT PRIVILEGES) -> db-migrate (alembic upgrade head
# от имени migration-роли) -> db-roles-finalize (тот же идемпотентный
# bootstrap-скрипт повторно — подхватывает только что созданные Alembic'ом
# таблицы/sequences и явно REVOKE на alembic_version) -> backend (только
# APP_DB_USER/APP_DB_PASSWORD, без прав DDL). depends_on с
# condition: service_completed_successfully делает эту цепочку
# детерминированной: следующий шаг не стартует, пока предыдущий не вышел с
# кодом 0.
# ------------------------------------------------------------------
db-roles-bootstrap:
# Stage 5 correction: no own "build:" here on purpose - this service
# must consume the exact same release image as "backend" (see that
# service's comment below and README, "Docker Compose"), not a
# separately-built image that merely happens to share a Dockerfile.
# "docker compose build backend" (or a plain "up -d", which builds any
# service still missing its image before starting anything) produces
# this tag once; every other service below only ever references it.
image: vibe-order-infra-backend:latest
command: ["python", "-m", "app.db_admin.bootstrap_roles"]
# Stage 4 correction: this one-shot service inherits the backend image's
# HEALTHCHECK (backend/Dockerfile - CMD ["python", "healthcheck.py"],
# which polls HTTP :8000/api/ready). This container never listens on
# 8000 at all (it runs bootstrap_roles.py, not uvicorn) and exits for
# good after doing its one job - Docker would keep probing a port that
# was never open and eventually record "unhealthy" even after a
# successful exit 0, which is misleading noise, not a real signal (the
# actual outcome is already the exit code Compose's own
# service_completed_successfully dependency below acts on). Disabling
# the inherited healthcheck here does not change backend's own
# healthcheck/lifecycle at all - each service's `healthcheck:` is
# independent.
healthcheck:
disable: true
# Stage 4: this image's CMD/all four launches always run as the
# unprivileged `appuser` (see backend/Dockerfile's USER appuser) and
# never write to their own container filesystem (no uploads, no local
# cache/log files - logs go to stdout, captured by the json-file
# driver below) - a pure Python process that needs zero Linux
# capabilities and no writable root fs, proven live (see the Stage 4
# report). /tmp is tmpfs only because Python's own stdlib (tempfile,
# some C extensions) can reach for it defensively even though this
# application never actually does.
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
read_only: true
tmpfs:
- /tmp
environment:
POSTGRES_USER: "${POSTGRES_USER:?POSTGRES_USER must be set}"
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set}"
POSTGRES_DB: "${POSTGRES_DB:?POSTGRES_DB must be set}"
POSTGRES_HOST: postgres
MIGRATION_DB_USER: "${MIGRATION_DB_USER:?MIGRATION_DB_USER must be set}"
MIGRATION_DB_PASSWORD: "${MIGRATION_DB_PASSWORD:?MIGRATION_DB_PASSWORD must be set}"
APP_DB_USER: "${APP_DB_USER:?APP_DB_USER must be set}"
APP_DB_PASSWORD: "${APP_DB_PASSWORD:?APP_DB_PASSWORD must be set}"
networks:
- app-net
depends_on:
postgres:
condition: service_healthy
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
db-migrate:
# Stage 5: same shared-image rationale as db-roles-bootstrap above.
image: vibe-order-infra-backend:latest
command: ["alembic", "upgrade", "head"]
# See db-roles-bootstrap's healthcheck/hardening comments above - same
# image, same fix, same reasoning.
healthcheck:
disable: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
read_only: true
tmpfs:
- /tmp
environment:
POSTGRES_DB: "${POSTGRES_DB:?POSTGRES_DB must be set}"
POSTGRES_HOST: postgres
MIGRATION_DB_USER: "${MIGRATION_DB_USER:?MIGRATION_DB_USER must be set}"
MIGRATION_DB_PASSWORD: "${MIGRATION_DB_PASSWORD:?MIGRATION_DB_PASSWORD must be set}"
networks:
- app-net
depends_on:
db-roles-bootstrap:
condition: service_completed_successfully
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
db-roles-finalize:
# Stage 5: same shared-image rationale as db-roles-bootstrap above.
image: vibe-order-infra-backend:latest
command: ["python", "-m", "app.db_admin.bootstrap_roles"]
# See db-roles-bootstrap's healthcheck/hardening comments above - same
# image, same fix, same reasoning.
healthcheck:
disable: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
read_only: true
tmpfs:
- /tmp
environment:
POSTGRES_USER: "${POSTGRES_USER:?POSTGRES_USER must be set}"
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set}"
POSTGRES_DB: "${POSTGRES_DB:?POSTGRES_DB must be set}"
POSTGRES_HOST: postgres
MIGRATION_DB_USER: "${MIGRATION_DB_USER:?MIGRATION_DB_USER must be set}"
MIGRATION_DB_PASSWORD: "${MIGRATION_DB_PASSWORD:?MIGRATION_DB_PASSWORD must be set}"
APP_DB_USER: "${APP_DB_USER:?APP_DB_USER must be set}"
APP_DB_PASSWORD: "${APP_DB_PASSWORD:?APP_DB_PASSWORD must be set}"
networks:
- app-net
depends_on:
db-migrate:
condition: service_completed_successfully
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
# ------------------------------------------------------------------
# Backend — FastAPI-приложение приёма заявок (см. backend/).
# Порт 8000 НЕ публикуется на host (нет "ports:") — доступен только
# другим контейнерам по внутреннему DNS-имени "backend" через
# app-net (доступ к postgres по hostname "postgres") и proxy-net
# (proxy_pass из Nginx — см. nginx/conf.d).
#
# Stage 2: подключается ИСКЛЮЧИТЕЛЬНО как runtime-роль (APP_DB_USER/
# APP_DB_PASSWORD, без прав DDL — см. app/db_admin/bootstrap_roles.py).
# Миграционный/владеющий креденшл (MIGRATION_DB_USER) backend никогда не
# видит. Схему больше не создаёт и не мутирует сам (см. app/main.py
# lifespan / app/core/schema_check.py) — ждёт, пока db-roles-finalize
# (а значит и db-migrate до него) успешно завершится.
#
# Stage 3: healthcheck ниже вызывает GET /api/ready изнутри контейнера
# (см. backend/healthcheck.py и backend/Dockerfile) — тот же read-only
# schema-check, что и app/core/schema_check.py::ensure_database_ready.
# Backend становится "healthy" для Compose/Nginx только когда реально
# готов обслуживать трафик, а не просто когда стартовал процесс Uvicorn.
#
# Stage 5 correction: an explicit "image:" pins the name/tag that ALL
# FOUR backend/database-lifecycle services below share (this one,
# db-roles-bootstrap, db-migrate, db-roles-finalize) - before this they
# each had their own bare "build: ./backend" with no "image:", so Compose
# generated four distinct default image names (one per service) despite
# docs describing "one release image". This is now the single service
# that ever builds it; the other three only reference the same tag (see
# their own comments above) - Compose builds it once, during "up"'s
# build phase, before any container in the dependency chain starts, so
# db-roles-bootstrap running first is never a race. Production delivery
# still retags a pulled release image onto this same local tag rather
# than building on the VPS - see README, "Порядок деплоя".
# ------------------------------------------------------------------
backend:
build: ./backend
image: vibe-order-infra-backend:latest
restart: unless-stopped
# Stage 4: see db-roles-bootstrap's matching comment above - same image,
# same unprivileged/no-local-writes reasoning, proven live serving real
# traffic (not just a one-shot exit) as part of this hardening pass.
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
read_only: true
tmpfs:
- /tmp
environment:
APP_DB_USER: "${APP_DB_USER:?APP_DB_USER must be set}"
APP_DB_PASSWORD: "${APP_DB_PASSWORD:?APP_DB_PASSWORD must be set}"
POSTGRES_DB: "${POSTGRES_DB:?POSTGRES_DB must be set}"
POSTGRES_HOST: postgres
# No fallback for the secret itself - an absent JWT_SECRET_KEY must
# fail `docker compose config`/`up` loudly, never start the backend
# with an empty/guessable value. Algorithm/lifetime are non-secret and
# already have matching safe defaults in Settings (app/core/config.py),
# so mirroring those defaults here is just documentation, not a
# separate source of truth.
JWT_SECRET_KEY: "${JWT_SECRET_KEY:?JWT_SECRET_KEY is required}"
JWT_ALGORITHM: "${JWT_ALGORITHM:-HS256}"
ACCESS_TOKEN_EXPIRE_MINUTES: "${ACCESS_TOKEN_EXPIRE_MINUTES:-30}"
networks:
- app-net
- proxy-net
depends_on:
db-roles-finalize:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "healthcheck.py"]
interval: 10s
timeout: 3s
retries: 3
start_period: 15s
deploy:
resources:
limits:
cpus: "0.50"
memory: 192M
reservations:
memory: 128M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
networks:
# Внешний контур: Nginx + Registry. Наружу торчит только Nginx (80/443),
# Registry внутри этой сети доступен Nginx, но не публикуется на host.
proxy-net:
driver: bridge
# Внутренняя сеть приложения: PostgreSQL + backend + pgAdmin.
# Не имеет точки входа снаружи, кроме опционального loopback-порта pgAdmin.
app-net:
driver: bridge
volumes:
postgres-data:
pgadmin-data:
registry-data: