Repository navigation
Expand file tree
/
Copy pathcompose.yaml
More file actions
592 lines (505 loc) · 16.9 KB
/
Copy pathcompose.yaml
File metadata and controls
592 lines (505 loc) · 16.9 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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/
# Here the instructions define your application as a service called "app".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
# ============================================================================
# Docker Compose for Production
# ============================================================================
# This file consolidates all concepts learned in Production:
# - Service configuration with healthchecks, restart policies and limits
# - Secrets management
# - Isolated networks and network security
# - Volumes and persistence
# - Log drivers
# ============================================================================
# ============================================================================
# NETWORK CONFIGURATION
# ============================================================================
networks:
# Frontend network: exposed to the external world via nginx
frontend:
driver: bridge
ipam:
config:
- subnet: 172.20.0.0/24
# Labels for documentation
labels:
com.docker.compose.network: "frontend"
description: "Public network for nginx and external access"
# Backend network: isolated, internal communication only
backend:
driver: bridge
ipam:
config:
- subnet: 172.21.0.0/24
# Isolation: only app and database communicate
internal: true # In real production, consider 'true' for total isolation
labels:
com.docker.compose.network: "backend"
description: "Private network for the app and database"
# ============================================================================
# VOLUME CONFIGURATION
# ============================================================================
volumes:
# ============================================================================
# Volume for PostgreSQL data
# ============================================================================
# IMPORTANT: In production, choosing the right storage is critical for performance,
# availability and backups of the database.
#
# OPTION 1: Native Docker Volume (CURRENT - Recommended for single-node)
# Better performance, Docker-managed, proper isolation
db-data:
driver: local
# Docker automatically manages at /var/lib/docker/volumes/
# Advantages:
# - Better performance (optimized by Docker)
# - Automatic permission handling
# - Integration with backup plugins
# - Portability between environments
labels:
description: "Persistent PostgreSQL data"
backup: "daily"
critical: "true"
# OPTION 2: Bind Mount with absolute path
# Use when you need full control over storage location
# db-data:
# driver: local
# driver_opts:
# type: none
# o: bind
# device: /var/lib/docker-volumes/postgres # ABSOLUTE path
# # Advantages:
# # - Full control over location (e.g., mount on dedicated SSD/NVMe)
# # - Easier automated backups using external scripts
# # - Useful for compliance (auditing physical data location)
# labels:
# description: "Persistent PostgreSQL data"
# OPTION 3: NFS - Network File System (Ideal for clusters/high availability)
# Use in distributed environments where multiple nodes need access to data
# file_storage:
# driver: local
# driver_opts:
# type: nfs
# o: addr=192.168.1.100,rw,nfsvers=4.1,hard,intr
# device: ":/mnt/nfs/file_storage"
# # Advantages:
# # - Shared storage across multiple nodes
# # - Enables failover and high availability
# # - Centralized backup on storage server
# # - Horizontal scalability
# # Disadvantages:
# # - Network latency (performance impact)
# # - Dependency on the NFS server (single point of failure)
# # - Requires additional security configuration
# labels:
# description: "File storage over NFS"
# OPTION 4: Block Storage (AWS EBS, DigitalOcean Volumes, GCP Persistent Disks)
# Use in cloud environments with managed high-performance volumes
# db-data:
# driver: local
# driver_opts:
# type: none
# o: bind
# device: /mnt/block-storage/postgres # Mounted external volume
# # PRE-REQUISITE: Mount the block storage volume on the host first:
# # sudo mkdir -p /mnt/block-storage
# # sudo mount /dev/disk/by-id/scsi-0DO_Volume_postgres-vol /mnt/block-storage
# #
# # Advantages:
# # - Guaranteed performance (dedicated IOPS)
# # - Automatic backup snapshots
# # - Dynamic size expansion
# # - Instance migration (attach/detach)
# # - Cloud provider availability SLA
# # Disadvantages:
# # - Additional costs per GB/IOPS
# # - Limited to a single availability zone
# # - Requires cloud provider configuration
# labels:
# description: "Persistent PostgreSQL data via Block Storage"
# Volume for application logs
# PRODUCTION: Docker-managed volume (safer and more portable)
app-logs:
driver: local
labels:
description: "Spring Boot application logs"
# Volume for Keycloak data (build configuration and cache)
keycloak-conf:
driver: local
labels:
description: "Keycloak build configuration"
backup: "recommended"
critical: "false"
# Volume for Keycloak runtime data (cache, temporary files)
keycloak-lib:
driver: local
labels:
description: "Keycloak runtime data"
backup: "recommended"
critical: "false"
# ============================================================================
# SECRETS
# ============================================================================
# Docker secrets (requires Swarm mode for native secrets)
# For dev/production without Swarm, external files are used
secrets:
db-password:
file: ./secrets/db-password.txt
api-db-password:
file: ./secrets/api-db-password.txt
keycloak-db-password:
file: ./secrets/keycloak-db-password.txt
keycloak-admin-password:
file: ./secrets/keycloak-admin-password.txt
# ============================================================================
# CONFIGURATION
# ============================================================================
# .env file is automatically loaded
# Variables may be replaced using ${VARIABLE:-default}
# ============================================================================
# SERVICES
# ============================================================================
services:
# ============================================================================
# NGINX - Reverse Proxy
# ============================================================================
nginx:
image: nginx:1.29-alpine
container_name: nginx
# Drop all capabilities (principle of least privilege)
cap_drop:
- ALL
cap_add:
- CAP_CHOWN
- CAP_SETUID
- CAP_SETGID
# Security options
security_opt:
- no-new-privileges:true # Prevent escalation
env_file:
- env_files/.env.nginx
# Restart policy
restart: unless-stopped
# Networks: connected to frontend (external) and backend (app)
networks:
- frontend
- backend
# Exposed ports
ports:
- "80:80"
- "443:443"
# Volumes
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- ./nginx/certs:/etc/nginx/certs:ro
- ./nginx/html:/usr/share/nginx/html:ro
# Dependencies
depends_on:
api:
condition: service_started # Changed from service_healthy because it doesn't work properly with multiple replicas
# Healthcheck
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# Resource limits
deploy:
resources:
limits:
cpus: '0.2'
memory: 256M
reservations:
cpus: '0.05'
memory: 64M
# Logging
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
labels: "service,tier,environment"
tag: "nginx"
# Labels for organization
labels:
service: "nginx"
tier: "frontend"
environment: "${ENVIRONMENT:-production}"
# ==========================================================================
# SPRING-BOOT APPLICATION
# ==========================================================================
api:
build:
context: .
dockerfile: Dockerfile
image: mcqueide/people-api:v1.1.0
# Drop all capabilities (principle of least privilege)
cap_drop:
- ALL
# Security options
security_opt:
- no-new-privileges:true # Prevent escalation
# User namespace (security best practice)
# user: "spring:spring" # Uncomment if image supports it
# Restart policy
restart: unless-stopped
# Networks: backend (db)
networks:
- backend
extra_hosts:
- "mcqueide.local:172.21.0.1"
# Ports: DO NOT expose externally in production
# ports:
# - "8081:8081" # ❌ For debug only, remove in production
# Ports (not externally exposed, only through nginx)
expose:
- "8081"
env_file:
- env_files/.env.api
secrets:
- api-db-password
# Volumes
volumes:
- app-logs:/app/logs
- ./nginx/certs:/certs:ro
# Dependencies
depends_on:
db:
condition: service_healthy
keycloak:
condition: service_healthy
# Resource limits
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
# Replica configuration (2 application instances)
# Note: deploy.replicas is fully supported only in Docker Swarm
# For Compose standalone, use: docker compose up -d --scale app=2
replicas: 2
# Configurations below only work in Docker Swarm:
# update_config:
# parallelism: 1
# delay: 10s
# order: start-first
# rollback_config:
# parallelism: 1
# delay: 5s
# Structured logging
logging:
driver: "json-file"
options:
max-size: "50m"
max-file: "5"
labels: "service,tier,environment"
tag: "{{.Name}}/{{.ID}}"
# Labels
labels:
service: "api"
tier: "backend"
environment: "${ENVIRONMENT:-production}"
version: "${API_VERSION:-1.0.0}"
# ==========================================================================
# POSTGRESQL - Database
# ==========================================================================
db:
image: postgres:17-alpine3.22
container_name: db
# Drop all capabilities (principle of least privilege)
cap_drop:
- ALL
# Add only required capabilities
cap_add:
- CAP_CHOWN
- CAP_FOWNER
- CAP_DAC_OVERRIDE
- CAP_SETUID
- CAP_SETGID
# Security
security_opt:
- no-new-privileges:true # Prevenir escalação
# - seccomp:seccomp-db-profile.json # Perfil seccomp customizado
# restart: unless-stopped
# Isolated backend network
networks:
- backend
# Ports: DO NOT expose externally in production
# ports:
# - "5432:5432" # ❌ For debug only, remove in production
expose:
- "5432"
user: postgres
# Secrets
secrets:
- db-password
- keycloak-db-password
- api-db-password
# Persistent volumes
volumes:
- db-data:/var/lib/postgresql/data
- ./postgres/init:/docker-entrypoint-initdb.d:ro # Initialization scripts
# Not required, docker uses .env by default
env_file:
- env_files/.env.db
# OPTIMIZATION: Use tmpfs for temporary data (improves performance)
# Sockets and temp files don't require persistence
tmpfs:
- /tmp
- /var/run/postgresql # Unix socket in memory for better performance
# Healthcheck
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-postgres}" ]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
# Resource limits
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
# Logging
logging:
driver: "json-file"
options:
max-size: "100m"
max-file: "3"
tag: "postgres"
# Labels
labels:
service: "postgres"
tier: "database"
# Shared memory size (important for PostgreSQL)
shm_size: 256mb
# ==========================================================================
# KEYCLOAK - Identity and Access Management
# ==========================================================================
keycloak:
image: quay.io/keycloak/keycloak:26.4
container_name: keycloak
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
restart: unless-stopped
networks:
- backend
expose:
- "8080"
# Ports: DO NOT expose externally in production
# ports:
# - "8080:8080" # ❌ For debug only, remove in production
secrets:
- keycloak-db-password
- keycloak-admin-password
env_file:
- env_files/.env.keycloak
volumes:
- keycloak-conf:/opt/keycloak/conf
- keycloak-lib:/opt/keycloak/lib/quarkus/
- ./keycloak/export:/opt/keycloak/data/import
# NOTE: Use 'start' for production (builds automatically on first run)
# After first successful build, you can optionally use 'start --optimized' for faster restarts
command: start-dev
# Run import
# command: start-dev --import-realm # Add --import-realm flag to import on startup
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "exec 3<>/dev/tcp/keycloak/9000 && echo -e 'GET /auth/health/ready HTTP/1.1\r\nHost: keycloak\r\nConnection: close\r\n\r\n' >&3 && cat <&3 | grep -q '200 OK'"]
interval: 30s
timeout: 10s
retries: 5
start_period: 90s # Keycloak takes time to initialize
deploy:
resources:
limits:
cpus: '0.5'
memory: 768M
reservations:
cpus: '0.25'
memory: 512M
logging:
driver: "json-file"
options:
max-size: "50m"
max-file: "3"
labels:
service: "keycloak"
tier: "backend"
environment: "${ENVIRONMENT:-production}"
# ==========================================================================
# KEYCLOAK EXPORT - One-time configuration export
# ==========================================================================
keycloak-export:
image: quay.io/keycloak/keycloak:26.4
container_name: keycloak-export
profiles:
- export # Only runs when explicitly called
networks:
- backend
secrets:
- keycloak-db-password
- keycloak-admin-password
env_file:
- env_files/.env.keycloak
volumes:
- ./keycloak/export:/opt/keycloak/data/import:rw
command: export --dir /opt/keycloak/data/import --users realm_file
depends_on:
db:
condition: service_healthy
# ============================================================================
# INITIALIZATION
# ============================================================================
#
# To start the application:
# docker compose up -d
#
# To start specific services:
# docker compose up -d app postgres nginx
#
# ============================================================================
# ============================================================================
# USEFUL COMMANDS
# ============================================================================
#
# Deploy with minimal downtime:
# docker compose up -d --no-deps --build app
#
# Logs:
# docker compose logs -f app
# docker compose logs --tail=100 postgres
#
# Database backup:
# docker compose exec postgres pg_dump -U $(cat secrets/db-user.txt) appdb > backup.sql
#
# Database restore:
# docker compose exec -T postgres psql -U $(cat secrets/db-user.txt) appdb < backup.sql
#
# Inspect PostgreSQL volume:
# docker volume inspect production_postgres_data
#
# Locate volume data:
# docker volume inspect production_postgres_data | grep Mountpoint
#
# Docker volume backup:
# docker run --rm -v production_postgres_data:/data -v $(pwd):/backup alpine tar czf /backup/postgres_backup.tar.gz -C /data .
#
# ============================================================================