docker-compose with Postgres
Learn how one Compose file starts an Axum app and a Postgres database together, how the app waits until the database is ready, and how the two containers talk to each other
Docker Compose is a tool that starts several containers from one file. Instead of starting Postgres by hand, then building the app image, then running it with the right flags, you describe both services in a file named compose.yaml and run one command. Compose reads the file, creates a small private network, starts the database, waits for it to be ready, and then starts the app with the database address already set.
Where This Fits
The Dockerfile page produced a single image that holds the compiled app. That image still needs a database to talk to, and on a laptop the database is usually a separate install with its own password, port, and data folder. Compose removes that split. The app and the database become two services in one file, started and stopped together, with the same settings on every machine that runs the file.
Think of a food stall that needs both a stove and a fridge. Running them separately means two trips, two plugs, and two chances to forget one. Compose is the single switch that turns both on in the right order and wires them together.
The Smallest Working Version
Start with a project that already has a Dockerfile that builds the app and runs it on port 3000. The Compose file adds a Postgres service next to it. Create compose.yaml in the project root, beside Cargo.toml.
# compose.yaml
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app_user
POSTGRES_PASSWORD: change-me-in-real-use
POSTGRES_DB: app_db
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 5
start_period: 10s
app:
build: .
environment:
DATABASE_URL: postgres://app_user:change-me-in-real-use@db:5432/app_db
LISTEN_ADDRESS: 0.0.0.0:3000
ports:
- "3000:3000"
depends_on:
db:
condition: service_healthy
volumes:
pgdata:
The app itself needs no changes beyond reading the settings it already reads. The same AppConfig from the configuration pages loads DATABASE_URL and LISTEN_ADDRESS from the environment, and the pool connects with the URL it is given.
// src/main.rs
use axum::{routing::get, Router};
use sqlx::PgPool;
#[tokio::main]
async fn main() {
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let listen_address = std::env::var("LISTEN_ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:3000".to_string());
let pool = PgPool::connect(&database_url)
.await
.expect("could not connect to Postgres");
let app = Router::new()
.route("/", get(|| async { "Hello!" }))
.route("/health", get(|| async { "OK" }))
.with_state(pool);
let listener = tokio::net::TcpListener::bind(&listen_address)
.await
.unwrap();
println!("Server running at http://{listen_address}");
axum::serve(listener, app).await.unwrap();
}
Start everything with one command, from the project root:
docker compose up --build
The terminal shows Postgres starting first, then the health check passing, then the app starting and printing its listening line. Open http://127.0.0.1:3000/health in a browser or run curl http://127.0.0.1:3000/health and the answer is OK. Stop everything with Ctrl+C, or with docker compose down from another terminal.
Docker Was Not Available for a Live Run Here:
Docker is not installed on the machine these pages were written on, so docker compose up was not run live while writing this page. The Compose file above was checked against the Compose specification, the Postgres service definition was checked against the Postgres image documentation, and the Rust code was run against a real local Postgres 16.15, where the same DATABASE_URL and pool code connected and answered queries. Treat the docker compose commands on this page as checked against the official docs, not as a run that happened here. Before you trust them on your own machine, run docker compose config to validate the file and docker compose ps after starting to confirm both services report healthy.
Working Setup:
If docker compose ps shows the db service as healthy and the app service as running, and curl http://127.0.0.1:3000/health prints OK, the whole stack works. The database accepted the app's connection, the app answered a request, and the two containers are talking over their private network.
Understanding the File Piece by Piece
The file has three levels that a beginner should learn to read. The top level holds services and volumes. Each service is one container, and each volume is one named chunk of storage that survives restarts.
The db service
db:
image: postgres:16
environment:
POSTGRES_USER: app_user
POSTGRES_PASSWORD: change-me-in-real-use
POSTGRES_DB: app_db
volumes:
- pgdata:/var/lib/postgresql/data
The image line names the Postgres image and its version. The tag 16 pins the major version, so a later Postgres 17 release does not silently change the database under the app. The three POSTGRES_ variables are read by the Postgres image the first time it starts with an empty data folder: they create a user, set that user's password, and create a database owned by that user. They only take effect on a fresh volume. Changing them later, while pgdata already holds data, does nothing, which surprises beginners who edit the password and wonder why the old one still works.
The volumes line maps the named volume pgdata to /var/lib/postgresql/data inside the container, which is where Postgres keeps its data files. Without this line, stopping and removing the container would delete the database. With it, docker compose down keeps the data, and the next docker compose up finds the same tables and rows.
The healthcheck
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 5
start_period: 10s
A health check is a command Compose runs inside the container on a schedule to decide whether the service is really ready. pg_isready is a small tool that ships inside the Postgres image. It tries to open a connection and exits with code 0 when the database accepts connections. The test list starts with CMD-SHELL, which runs the rest as a shell command inside the container.
The timing keys control the schedule. interval is how often the check runs, timeout is how long one check may take, retries is how many failures in a row mark the container unhealthy, and start_period is a grace window after startup during which failures do not count. Postgres needs a few seconds on its first start to initialise its data folder, so a start_period of 10 seconds keeps those early failures from counting against it.
The doubled dollar signs need a plain explanation, because they look like a typo. Compose treats a single $ in the file as the start of a variable to fill in from your own shell, so $POSTGRES_USER would be replaced before the container ever sees it. Writing $${POSTGRES_USER} tells Compose to pass a literal $POSTGRES_USER through, and the shell inside the container then reads the variable from the container's own environment. One dollar is Compose's variable, two dollars is the container's variable.
The app service
app:
build: .
environment:
DATABASE_URL: postgres://app_user:change-me-in-real-use@db:5432/app_db
LISTEN_ADDRESS: 0.0.0.0:3000
ports:
- "3000:3000"
depends_on:
db:
condition: service_healthy
The build line tells Compose to build an image from the Dockerfile in the current folder, instead of pulling a ready-made image. The environment lines set variables inside the app container. The database address uses db as the hostname, not localhost, because Compose gives every service a name on the shared network, and that name resolves to the database container. Port 5432 is the port Postgres listens on inside its own container, so no port mapping is needed for the app to reach it.
The ports line maps a port on your own machine to a port in the container. "3000:3000" means requests to port 3000 on your laptop reach port 3000 inside the app container. The quotes matter in YAML, because an unquoted 3000:3000 can be misread. The LISTEN_ADDRESS of 0.0.0.0:3000 is equally important: inside a container, binding to 127.0.0.1 means only the container itself can connect, and the port mapping would never deliver a request. Binding to 0.0.0.0 means all interfaces, so the mapped port works.
The depends_on block is the ordering rule, and its long form is the whole point of this page. The short form, depends_on: [db], only waits until the database container has started, which is not the same as ready. Postgres takes seconds to initialise, and an app that connects during those seconds fails at startup. The long form with condition: service_healthy makes Compose wait until the health check passes before it creates the app container at all.
The Concept Behind the File
Compose turns a running system into a text file. The file names every part, every setting, and every connection between parts, so the same system can be recreated on another machine by copying the file and running one command. Nothing about the setup lives only in somebody's shell history or in a set of commands typed once and forgotten.
A beginner can think of the file as a recipe card for a whole meal, not one dish. Each service is one dish, the network is the table they share, the volume is the pantry that keeps ingredients between meals, and the health check is tasting the soup before serving it. The recipe does not cook anything by itself. It tells Compose exactly what to cook, in what order, and how to know when each part is done.
Why This Design
Running the app and the database as two containers keeps their concerns apart. The database image is maintained by the Postgres team, the app image is built from the project, and either one can be replaced without touching the other. The shared network keeps their traffic off the laptop's network, and the named volume keeps the data safe while the containers come and go.
The alternative most beginners reach for first is installing Postgres directly on the laptop and pointing the app at localhost. That works for one person on one machine, and it breaks the moment a second person joins, or the laptop is replaced, or the app moves to a server. The Compose file travels with the project in version control, so every machine that checks out the code gets the same database version, the same user, and the same startup order.
Never Commit a Real Password in This File:
The password in the example is a placeholder. A real password written in compose.yaml and committed to version control is visible to everyone who can read the repository, and changing it later does not erase it from the history. Keep real passwords in a .env file that is listed in .gitignore, and read them into Compose with the ${POSTGRES_PASSWORD} syntax shown below.
A Richer Complete Example
Real projects add three things to the small version: secrets from a file, a migration step that runs before the app, and a way to inspect the database from the laptop.
# .env
POSTGRES_USER=app_user
POSTGRES_PASSWORD=a-long-random-password
POSTGRES_DB=app_db
# compose.yaml
services:
db:
image: postgres:16
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 5
start_period: 10s
migrate:
build: .
command: ["./migrate.sh"]
environment:
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
depends_on:
db:
condition: service_healthy
app:
build: .
environment:
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
LISTEN_ADDRESS: 0.0.0.0:3000
RUST_LOG: info
ports:
- "3000:3000"
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
restart: unless-stopped
volumes:
pgdata:
The .env file sits beside compose.yaml, and Compose reads it automatically. ${POSTGRES_PASSWORD} in the file is filled in from that file, so no secret appears in the Compose file itself. Add .env to .gitignore before the first commit.
The migrate service is a third container built from the same image, but it runs a migration script instead of the server. Its depends_on has a different condition, service_completed_successfully, which waits until the migration container runs and exits with code 0. The app then depends on both the database being healthy and the migrations having finished, so it never serves requests against a database whose tables do not exist yet. The script itself is small:
# migrate.sh
#!/bin/sh
set -e
psql "$DATABASE_URL" -f migrations/001_create_users.sql
The command line replaces the image's default command for that service only, so the same image serves as both the server and the migration runner. The restart: unless-stopped line on the app tells Compose to restart the app if it crashes, and to keep it stopped if you stopped it on purpose. The ports line on the database exposes Postgres on the laptop's port 5432, which lets a database tool on the laptop connect directly for inspection. That mapping is for development only. In shared or public environments, leave the database port unmapped so only the app container can reach it.
Everyday Commands
Compose has a small set of commands that cover daily work. Each one takes the same file and does one obvious thing.
docker compose up --build
Builds the app image if the code changed, starts every service, and shows all their logs mixed together in the terminal. Add -d to run in the background and get the terminal back.
docker compose ps
Lists the services, their state, and their health. This is the first command to run when something does not answer, because it shows whether the database is healthy, starting, or unhealthy.
docker compose logs app
Shows only the app's logs. Add -f to follow them live, the same way tail -f follows a file.
docker compose exec db psql -U app_user -d app_db
Runs a command inside a running container. This one opens the psql prompt inside the database container, where a query like SELECT count(*) FROM users; runs against the real data.
docker compose down
Stops every service and removes the containers and the network, but keeps the pgdata volume, so the data survives. The command that deletes the data is docker compose down -v, with the -v flag removing named volumes too. That flag is the one to double-check before pressing Enter, because the data it deletes cannot be recovered from Compose.
The File Can Also Be Named docker-compose.yaml:
Compose accepts compose.yaml, compose.yml, docker-compose.yaml, and docker-compose.yml, and uses the first one it finds. The short name compose.yaml is the current convention in the Compose specification. The older docker-compose spelling with a hyphen belongs to the first version of the tool, and the current command is docker compose with a space, which is a subcommand of Docker itself.
Checking the File Without Starting Anything
Two commands verify the setup before any container runs. The first checks the file itself:
docker compose config
This prints the file back with every variable filled in and every relative path resolved. If a variable is missing, Compose warns about it here instead of failing halfway through startup. If the password shows up in this output, remember that the output itself is a place secrets can leak, so do not paste it into a chat log or a bug report.
The second check is the app's own behaviour. Once the stack is up, these three requests confirm each layer:
curl http://127.0.0.1:3000/health
curl http://127.0.0.1:3000/
docker compose exec db pg_isready -U app_user -d app_db
The first proves the app answers. The second proves the app serves its real route. The third proves the database accepts connections from inside its own container. When all three pass, the wiring is right, and any later failure is in the app's own code rather than in the Compose setup.
How the Pieces Connect
The whole stack is four parts and three connections. Reading the flow from left to right shows where a request travels and where the database sits.
Your laptop
|
| http://127.0.0.1:3000
v
app container (port 3000, binds 0.0.0.0)
|
| DATABASE_URL host is "db", port 5432
v
db container (Postgres 16, pgdata volume)
|
| healthcheck runs pg_isready every 5s
v
Compose waits for healthy, then starts app
The browser never talks to the database, and the database never listens on the laptop's network unless the ports mapping is added. The app is the only bridge between the two, which is exactly the shape a real deployment has.
Common Beginner Mistakes
Using localhost as the database host inside the app
# Wrong - localhost inside the app container means the app container itself
environment:
DATABASE_URL: postgres://app_user:change-me-in-real-use@localhost:5432/app_db
Inside a container, localhost means that container, not the laptop and not the database container. The app would try to connect to a Postgres running inside its own container, find nothing listening, and fail. The fix is the service name, db, which Compose resolves to the database container on the shared network.
Using the short depends_on and hitting the startup race
# Wrong - the app starts as soon as the db container starts, before Postgres is ready
depends_on:
- db
The short form only orders container creation. On a fast machine the app may start after Postgres is already ready and the bug never shows, then fail on a slower machine or on the very first start, when Postgres is still creating its data folder. The fix is the long form with condition: service_healthy and a health check on the database, as in the examples above.
Binding the app to 127.0.0.1 inside the container
// Wrong - inside a container this hides the server from the port mapping
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
The default from local development binds to the loopback interface, which is correct on a laptop and wrong in a container. The port mapping forwards traffic to the container's external interface, and a server bound only to loopback never receives it. The fix is 0.0.0.0:3000, either in code or through the LISTEN_ADDRESS variable, as the examples use.
Changing the database password after the first start
Editing POSTGRES_PASSWORD in the Compose file and running docker compose up again changes nothing if the pgdata volume already exists, because the Postgres image only reads those variables when it creates a fresh data folder. The fix is either to change the password inside the running database with SQL, or to delete the volume with docker compose down -v and start fresh, accepting that all data is lost.
Expecting depends_on to help after startup
The health check gate only applies when the stack starts. If the database container restarts later, while the app is already running, Compose does not restart the app or pause its requests. The app must handle a database that goes away and comes back, by retrying connections or by failing its readiness check until the pool recovers. The pool's own reconnect behaviour and the health check route are the tools for that, not depends_on.
Final Complete Example
Here is the full stack in one place: the Compose file, the app, and the commands to run it. The .env file holds the secrets, the Compose file holds the shape, and the app reads its settings from the environment exactly as it does outside Compose.
# compose.yaml
services:
db:
image: postgres:16
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 5
start_period: 10s
app:
build: .
environment:
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
LISTEN_ADDRESS: 0.0.0.0:3000
RUST_LOG: info
ports:
- "3000:3000"
depends_on:
db:
condition: service_healthy
restart: unless-stopped
volumes:
pgdata:
# .env
POSTGRES_USER=app_user
POSTGRES_PASSWORD=a-long-random-password
POSTGRES_DB=app_db
docker compose up --build
docker compose ps
curl http://127.0.0.1:3000/health
docker compose down
Run those four commands in order and the stack builds, starts, proves itself healthy, and stops cleanly with its data kept in the pgdata volume for the next start.
Summary
The single most useful idea on this page is the difference between started and ready. A container can be running while the program inside it is still warming up, and any setup that treats those two states as the same will fail at the worst moment, usually the first start on a fresh machine. The health check is what turns a guess into a fact, and condition: service_healthy is what makes Compose act on that fact before starting the app.
That split shows up everywhere in deployment work. The database has its own readiness signal, the app has its own health route, and the platforms in the coming pages each have their own way of asking whether a service is ready before sending it traffic. Once the habit is in place, checking readiness before depending on something, the Compose file becomes the smallest place where the whole system can be described, started, and torn down with one command each, and the same file that runs the stack on a laptop is the starting point for the deployment files that run it on a server.