Docker Compose 101: services, depends_on, healthcheck và network
docker run
phù hợp để học một container. Khi application có app, database, environment variable, volume, network và startup dependency, command line nhanh chóng thành thứ không ai muốn đọc lại sau một tuần. Docker Compose đưa mô tả stack vào YAML. File Compose không thay Dockerfile. Dockerfile mô tả cách build image; Compose mô tả container nào chạy cùng nhau, dùng image nào, mount gì, network nào, dependency nào và port nào được publish. Lab này dựng một Node.js HTTP app gọi PostgreSQL. Nó đủ nhỏ để chạy local, nhưng có healthcheck, named volume và private database network giống nguyên tắc production. ## Cấu trúc lab
text compose-101/ ├── compose.yaml ├── Dockerfile ├── package.json ├── package-lock.json └── server.js
package.json
:
json { "name": "compose-101", "private": true, "type": "module", "scripts": { "start": "node server.js" }, "dependencies": { "pg": "8.16.0" } }
server.js
:
js import http from "node:http"; import pg from "pg"; const { Pool } = pg; const port = Number(process.env.PORT || 3000); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); async function databaseReady() { await pool.query("select 1"); } const server = http.createServer(async (request, response) => { if (request.url === "/livez") { response.writeHead(200).end("ok"); return; } if (request.url === "/readyz") { try { await databaseReady(); response.writeHead(200).end("ready"); } catch { response.writeHead(503).end("database unavailable"); } return; } response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify({ ok: true })); }); server.listen(port, "0.0.0.0", () => console.log(listening on ${port}));
Dockerfile
:
dockerfile FROM node:24-bookworm-slim WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY server.js ./ USER node EXPOSE 3000 CMD ["node", "server.js"]
Compose file tối giản nhưng có dependency đúng
compose.yaml
:
yaml services: app: build: context: . environment: NODE_ENV: production PORT: "3000" DATABASE_URL: postgres://demo:change-me-locally@postgres:5432/demo depends_on: postgres: condition: service_healthy ports: - "127.0.0.1:3000:3000" healthcheck: test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/livez').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"] interval: 15s timeout: 3s retries: 5 start_period: 10s networks: - internal postgres: image: postgres:16-alpine environment: POSTGRES_DB: demo POSTGRES_USER: demo POSTGRES_PASSWORD: change-me-locally volumes: - postgres_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] interval: 10s timeout: 3s retries: 10 start_period: 10s networks: - internal volumes: postgres_data: networks: internal:
Password trong lab chỉ tồn tại để ví dụ có thể chạy ngay. Không copy pattern này sang production
.env
hoặc Git repository. Production secret cần được inject từ secret mechanism của runtime. ##
services
: đơn vị runtime trong một project Mỗi service thường tạo một hoặc nhiều container theo cấu hình. Trong lab: -
app
build từ Dockerfile local. -
postgres
pull official image. Compose đặt tên network, volume và container theo project name. Project name mặc định lấy từ tên thư mục, nhưng có thể override qua
name:
hoặc
COMPOSE_PROJECT_NAME
. Điều này hữu ích cho staging/prod isolation, nhưng không thay thế việc tách credentials và data thực sự. ##
depends_on
không chỉ là thứ tự dòng YAML
depends_on
biểu đạt dependency lifecycle. Với condition
service_healthy
, Compose chờ healthcheck của Postgres pass trước khi start app.
yaml depends_on: postgres: condition: service_healthy
Nếu chỉ viết:
yaml depends_on: - postgres
Compose chỉ bảo đảm Postgres container start trước app container. “Container start” không đồng nghĩa Postgres đã sẵn sàng nhận TCP connection/query. Database có thể còn initialize data directory trong vài giây. Ngay cả
service_healthy
cũng không thay thế application retry hoặc error handling. Network transient, database restart sau đó, credential lỗi hay connection pool exhaustion vẫn xảy ra.
depends_on
giải quyết startup ordering local; app vẫn phải xử lý dependency failure lúc runtime. ## Healthcheck: process sống khác service sẵn sàng Lab có hai endpoint: -
/livez
: Node process đang nhận HTTP request. -
/readyz
: Node process query database được ngay tại thời điểm check. Docker healthcheck cho app dùng
/livez
, còn dependency startup dùng Postgres
pg_isready
. Đây là lựa chọn có chủ ý để minh họa khái niệm. Với load balancer production, chọn readiness endpoint nào là product/operational decision. Nếu app có fallback content khi database tạm unavailable, một readiness check bắt buộc database healthy có thể lấy app khỏi target group dù app vẫn phục vụ degraded response hợp lệ. Ngược lại, endpoint luôn trả 200 có thể đưa traffic vào app chưa init xong. Không có endpoint “đúng cho mọi app”. Có requirement rõ mới có endpoint đúng. [HÌNH 1 — Liveness và readiness] Tên file gợi ý:
docker-compose-liveness-readiness.webp
text Node process live? -> /livez -> 200 Node + DB ready? -> /readyz -> 200 hoặc 503 Postgres accepts query? -> pg_isready
Network và service name Cả app và Postgres ở
internal
network. Compose tạo DNS record theo service name, vì vậy app dùng hostname
postgres
trong URL:
text postgres://demo:password@postgres:5432/demo
Không dùng
localhost
trong
DATABASE_URL
của app container. Trong container app,
localhost
là app container, không phải Postgres container. Postgres không có
ports:
. App vẫn kết nối được vì cùng internal network. Host laptop/VPS không thể kết nối
localhost:5432
từ bên ngoài trừ khi tôi publish explicit port. Đây là boundary tốt cho một database không cần public access. App có port publish
127.0.0.1:3000:3000
, nên chỉ host local gọi được. Nếu cần public traffic, đặt reverse proxy/load balancer trước thay vì mở trực tiếp database hoặc app debug port ra Internet. [HÌNH 2 — Compose network] Tên file gợi ý:
docker-compose-app-postgres-network.webp
text host loopback :3000 | v app :3000 -- internal network --> postgres :5432 | v postgres_data volume
Named volume giữ database data qua recreate
yaml volumes: - postgres_data:/var/lib/postgresql/data
Container Postgres có thể bị stop/recreate khi đổi image/config; data vẫn nằm trong named volume nếu volume được giữ lại. Kiểm tra Compose volume:
bash docker compose config --volumes docker volume ls
Không chạy
docker compose down -v
khi muốn giữ data. Flag
-v
xóa named volume của project. Trong lab, đó là reset sạch. Trong environment có database thật, nó là destructive operation. ##
docker compose config
là lệnh nên chạy trước
up
Compose file có variable interpolation, override, profile, merge file và default value. Đọc YAML gốc chưa chắc cho thấy cấu hình Docker sẽ nhận.
bash docker compose config docker compose config --services docker compose config --volumes docker compose config --quiet
config
render cấu hình đã resolve. Cẩn thận vì output có thể chứa environment values/secret. -
--services
liệt kê service cuối cùng. -
--volumes
liệt kê volume cuối cùng. -
--quiet
chỉ validate, phù hợp CI/local check không muốn in config nhạy cảm. Khởi động lab:
bash docker compose up --build -d docker compose ps docker compose logs --tail=100 app postgres curl -i http://127.0.0.1:3000/livez curl -i http://127.0.0.1:3000/readyz
Dọn lab nhưng giữ data:
bash docker compose down
Dọn lab và xóa database data, chỉ dùng khi cố ý reset:
bash docker compose down -v
restart
policy không phải HA Compose có restart policy như
unless-stopped
để Docker restart container khi process crash hoặc daemon restart. Nó hữu ích trên một host, nhưng không tạo multi-host availability, không replicate database và không chống host disk failure.
yaml restart: unless-stopped
Đừng dùng restart loop để che application config lỗi. Nếu process crash vì migration error, invalid secret hoặc database schema incompatibility, restart policy chỉ tạo log noise cho tới khi disk đầy hoặc operator can thiệp. ## Từ lab sang Compose thật Khi đọc Compose production, tôi sẽ lần theo cùng các câu hỏi: 1. Service nào có public
ports
, service nào chỉ internal? 2. Volume nào giữ source of truth, volume nào là cache? 3. Service nào chờ healthcheck, healthcheck đang chứng minh điều gì? 4. Init job nào phải thành công trước app? 5. App gọi dependency bằng service name nào? 6. Image có build trên host hay pull immutable artifact từ registry? 7.
restart
, resource, secret và backup policy có phù hợp môi trường không? Đây là lý do Docker Compose 101 cần một app+DB lab trước. Khi gặp file Compose dài, tôi không cần học YAML bằng cách nhìn 200 dòng cùng lúc. Tôi lần theo service, mount, network, dependency và lifecycle. ## Những lỗi cần tránh ### Dùng
depends_on
thay retry logic Database có thể unavailable sau startup. App cần timeout/error handling/retry phù hợp thay vì tin Compose giải quyết mọi outage. ### In
docker compose config
vào public CI log Rendered config có thể chứa value từ
.env
. Dùng
docker compose config --quiet
cho validation hoặc redact output trước khi lưu. ### Publish database port vì app “không kết nối được” Sửa hostname thành service name
postgres
, kiểm tra network và healthcheck trước. Port publish không cần thiết cho app-to-app traffic. ### Gọi
down -v
trong thao tác routine Đó là lệnh reset state, không phải cleanup vô hại. ## Checklist cuối bài - [ ] Biết Dockerfile build image, Compose mô tả stack runtime. - [ ] Dùng được service name thay vì
localhost
để app gọi database. - [ ] Phân biệt container started với dependency healthy. - [ ] Tạo được named volume cho Postgres. - [ ] Chạy
docker compose config --quiet
trước
up
. - [ ] Biết
docker compose down -v
xóa data volume. - [ ] Không coi restart policy là high availability. ## Bài tiếp theo Phần nền tảng Docker đã đủ để bước sang Compose thật của LinuxUnity. Bài 1.6 sẽ đọc network, volume, lifecycle và image/deploy policy từ cấu hình production thay vì một lab tối giản.