Database service
- Docker & Kubernetes course
- Beginner
- Lesson 63/82
- 4 min
Add a database service to the compose file.
The database service
The database service uses a ready image, is configured with environment variables, and keeps its data in a named volume. The volume must also be declared under volumes: at the end of the file:
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: gizli
POSTGRES_DB: app
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:Dependency and health check
depends_on sets the start order. But the database container starting doesn't mean it's ready to accept connections; with healthcheck and condition: service_healthy, the API starts when the database is really ready:
db:
image: postgres:16
healthcheck:
test: ["CMD", "pg_isready", "-U", "app"]
interval: 5s
retries: 5
api:
build: .
depends_on:
db:
condition: service_healthyPractice Add the database
Write the db service in compose.yaml: image postgres:16; POSTGRES_PASSWORD: gizli under environment; the pgdata volume mounted at /var/lib/postgresql/data. At the end of the file, add the pgdata: declaration under a top-level volumes:.
Starter code
# compose.yaml
services:
# buraya yazSample solution
# compose.yaml
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: gizli
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:Expected output
[+] Running 2/2 ✔ Volume "proje_pgdata" Created ✔ Container proje-db-1 Started
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With which address does the API service connect to the database?
- By the service name: db:5432 Correct answer
- localhost:5432
- With the host's IP
- It can't connect without publishing the port
Explanation: Compose puts services on a shared network; the service name is the DNS name.
2 Start the API when the database is healthy.
depends_on:
db:
condition: ____
depends_on:
db:
condition: service_healthy
Explanation: service_started only waits for the start.
3 Match.
| Term | Meaning |
|---|---|
depends_on |
Start order |
healthcheck |
Readiness test |
pg_isready |
PostgreSQL ready command |
db:5432 |
Address by service name |