Docker Postgres for tests
Learn how to run Postgres in a Docker container for Axum tests, what each part of the run command does, and how the testcontainers crate starts the same container from Rust
Docker runs Postgres inside a container, which is a sealed box that holds the database server, its files, and its settings, separate from the rest of the machine. A test that needs Postgres starts a container, runs against it, and stops it when the test ends. Nothing is installed on the host machine, and two projects can run two different Postgres versions at the same time without interfering.
Where This Fits
The last page gave each test its own database, but all those databases still lived on one Postgres server that someone had to install and keep running. A developer who clones the project on a fresh machine has to install Postgres, create a user, and create a database before the first test passes. Docker removes that setup. The container carries the server, and the test command starts it.
Think of a food truck instead of a restaurant kitchen. The kitchen is fixed to one building, and anyone who wants to cook there has to go to it. The truck carries its own kitchen, parks wherever it is needed, and drives away when the work is done. A Docker container is the truck, and the Postgres server inside it is the kitchen.
Docker Was Not Run While Writing This Page:
Docker is not installed on the machine these docs were written on, and the docker command does not exist there. The Docker commands on this page were read from the official Postgres image docs on Docker Hub and the testcontainers docs, and the Rust code that talks to a container was compile-checked, but no container was started and no docker run output was observed here. The page says plainly where the verification stops, and it shows the equivalent test run against the local Postgres server that was verified instead. Run the commands on a machine with Docker installed and compare the output with the expected output below.
The Smallest Working Version
The official Postgres image on Docker Hub is named postgres, and the tag picks the version. The tag 16 means Postgres 16, which matches the server version the rest of this work uses. The command below starts a container in the background, names it, sets a password and a database, and maps the container port to a host port.
docker run --name axum-test-db \
-e POSTGRES_PASSWORD=axumdocs \
-e POSTGRES_USER=axumdocs \
-e POSTGRES_DB=ch19_tests \
-p 5433:5432 \
-d postgres:16
Each flag does one job. The --name axum-test-db flag gives the container a name, so later commands can refer to it instead of a generated id. The -e flags set environment variables inside the container, and the Postgres image reads them when it first starts. The -p 5433:5432 flag maps port 5433 on the host to port 5432 inside the container, which is the port Postgres listens on. The -d flag runs the container in the background, so the terminal returns at once. The final argument is the image and tag.
The three environment variables come from the image docs, and only one of them is required. POSTGRES_PASSWORD is required, and it sets the superuser password. Without it the container refuses to start. POSTGRES_USER is optional, and it creates a user with superuser power plus a database with the same name. Without it the default user is postgres. POSTGRES_DB is optional, and it names the default database created when the image first starts. Without it the database name defaults to the value of POSTGRES_USER. The variables only take effect when the container starts with an empty data directory. A container started again with existing data keeps the old database and ignores new values.
The connection string for this container points at the mapped host port, not the container port. The test code on the host reaches the container through port 5433.
postgres://axumdocs:axumdocs@127.0.0.1:5433/ch19_tests
The only difference from the local server string is the port. The user, the password, and the database name are the same, because the environment variables set them to the same values. A test that reads its connection string from DATABASE_URL needs no code change to run against the container. Only the variable changes.
Check that the container is ready before running tests. Postgres takes a few seconds to start, and a test that connects too early fails with a refused connection.
docker logs axum-test-db
The log line that means the server is ready reads like this, and it comes from the official image docs.
database system is ready to accept connections
A second check connects with psql from inside the container, using the container's own tools instead of the host's.
docker exec -it axum-test-db psql -U axumdocs -d ch19_tests -c "SELECT version();"
The output names the Postgres version the container runs. With the postgres:16 tag that is a 16.x release, and the exact patch version depends on when the image was pulled.
Stop and remove the container when the tests are done. A stopped container keeps its data, and a removed container throws it away.
docker stop axum-test-db
docker rm axum-test-db
Expected Output, Not Observed Output:
The log line and the version output above are what the official image docs describe, not output observed on the machine these docs were written on, because that machine has no Docker. On a machine with Docker, the log line appears a few seconds after the run command, and the version query prints the server version. If the log shows a password error instead, the POSTGRES_PASSWORD variable was missing or empty, which is the one variable the image requires.
Understanding the Run Command Piece by Piece
Three parts of the command cause most beginner confusion, and each one is worth a closer look. The port mapping, the password variable, and the background flag all look small, and each one changes what the test can do.
The port mapping
-p 5433:5432
The number before the colon is the host port, and the number after it is the container port. Postgres inside the container always listens on 5432, and the mapping decides which host port reaches it. The host port 5433 is picked because the local Postgres server already uses 5432, and two programs cannot share one port. A test that points at 5432 reaches the local server, and a test that points at 5433 reaches the container. Mixing the two up is the most common mistake on this page, and the symptom is a test that passes against the wrong database.
The password variable
-e POSTGRES_PASSWORD=axumdocs
The image refuses to start without a password, because a database with no password would accept connections from anyone who reaches the port. The password here is a local test password, and it never leaves the developer's machine. The same value appears in the connection string, because the test has to prove it knows the password to connect.
The background flag
-d postgres:16
The -d flag detaches the container, so the command returns at once and the terminal stays usable. Without it the container holds the terminal and prints its logs until it is stopped, which is useful for watching the first start and annoying for running tests. A detached container keeps running until it is stopped, so a forgotten container keeps holding its port and its memory. The docker ps command lists running containers, and it is the fastest way to find a forgotten one.
docker ps
The Concept Behind Containers for Tests
A test database needs a server, and a server needs installing. Installing Postgres on every developer machine and every build machine is slow, and the installs drift apart. One machine runs Postgres 16, another runs 15, and a test that passes on one fails on the other for a version reason, not a code reason. A container fixes the version. The image tag names the version, every machine pulls the same image, and every test runs against the same server.
The container also fixes cleanup. A local Postgres server accumulates databases, users, and rows across projects, and a test database left behind can collide with a later one. A container holds its own data directory, and removing the container removes all of it. The next run starts from the same empty state as the first run.
The trade is that Docker must be installed and running. A machine without Docker cannot run these tests at all, and a build machine that blocks Docker needs a different approach. The local Postgres server from the earlier pages is that approach, and the two can live side by side. The same tests run against either one, because only the connection string changes.
A Container That Deletes Itself
A test container is temporary by nature, and the --rm flag matches that nature. It removes the container as soon as it stops, so no cleanup command is needed afterwards.
docker run --rm --name axum-test-db \
-e POSTGRES_PASSWORD=axumdocs \
-e POSTGRES_USER=axumdocs \
-e POSTGRES_DB=ch19_tests \
-p 5433:5432 \
-d postgres:16
The difference from the earlier command is one flag, and the behaviour changes in one way. Stopping the container deletes it, including its data. A container started without --rm keeps its data across restarts, which helps when the database is reused across many test runs. A container started with --rm always starts empty, which helps when each run must start clean.
A named volume is the middle ground. It keeps the data outside the container, so the container can be removed and recreated without losing the database.
docker run --name axum-test-db \
-e POSTGRES_PASSWORD=axumdocs \
-e POSTGRES_USER=axumdocs \
-e POSTGRES_DB=ch19_tests \
-p 5433:5432 \
-v axum-test-data:/var/lib/postgresql/data \
-d postgres:16
The -v flag mounts a volume named axum-test-data at the data directory inside the container. The data survives the container, and the volume is deleted only with an explicit docker volume rm axum-test-data command. A volume is useful for a database that is reused across runs, and it is the wrong choice for a test that must start empty, because the old data is still there on the next run.
Starting the Container with Compose
A compose file holds the same settings as the run command, in a file the project can commit. The team runs one command instead of remembering a long run line, and the settings stay the same for everyone.
services:
postgres:
image: postgres:16
container_name: axum-test-db
environment:
POSTGRES_PASSWORD: axumdocs
POSTGRES_USER: axumdocs
POSTGRES_DB: ch19_tests
ports:
- "5433:5432"
Start it with the compose command, naming the file because it is not the default docker-compose.yml.
docker compose -f docker-compose.test.yml up -d
Stop it with the matching down command, which stops and removes the container.
docker compose -f docker-compose.test.yml down
The compose file holds the same password as the run command, and the same warning applies. A compose file for tests holds a local password, and it should not be committed with a real secret in it. For a local test database the risk is small, and the file is still worth a second look before committing.
Starting the Container from Rust with testcontainers
The testcontainers crate starts a container from inside the test, instead of the developer starting it by hand. The test starts the container, reads the mapped port, builds a connection string from it, and runs. When the test ends, the container value goes out of scope and the container is stopped and removed. No terminal command is needed, and no container is left behind.
The crate for Postgres is testcontainers-modules, version 0.15.0, and the postgres feature turns on the Postgres module. The testcontainers crate itself is re-exported through it, so no separate dependency is needed.
[dev-dependencies]
testcontainers-modules = { version = "=0.15.0", features = ["postgres"] }
The Postgres module defaults to the database, user, and password all named postgres, which the module docs state directly. The async runner starts the container, and the test reads the host and the mapped port from the running container.
use testcontainers_modules::{
postgres::Postgres, testcontainers::runners::AsyncRunner,
};
#[tokio::test]
async fn testcontainers_postgres_starts_a_container() {
let container = Postgres::default().start().await.unwrap();
let host = container.get_host().await.unwrap();
let port = container.get_host_port_ipv4(5432).await.unwrap();
let database_url = format!("postgres://postgres:postgres@{host}:{port}/postgres");
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
let (one,): (i32,) = sqlx::query_as("SELECT 1")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(one, 1);
}
The port is mapped to a random host port, not a fixed one, because the test does not pick it. The get_host_port_ipv4(5432) call asks the container which host port maps to the container port 5432, and the connection string is built from the answer. That is the part beginners miss. The connection string cannot be written as a constant here, because the port is only known after the container starts.
The container value must stay alive for the whole test. It owns the running container, and dropping it stops and removes the container. A test that drops the container before its last query fails with a closed connection, and the fix is to keep the value in a variable until the test ends.
The get_host and get_host_port_ipv4 calls are async in the 0.15.0 async runner, so they need .await. The sync form in the module docs uses SyncRunner instead, with the same calls and no .await, and it fits a test that is not async. The async form fits this project, because the tests already run on Tokio.
This Snippet Compiles but Was Not Run Here:
The testcontainers snippet above was compile-checked against testcontainers-modules 0.15.0, and it compiles. It was not run on the machine these docs were written on, because running it needs a Docker daemon and there is none. In the scratch project it is marked ignored, so cargo test skips it instead of failing. On a machine with Docker, remove the ignore marker and run it. The first run pulls the postgres image, which takes a while, and later runs reuse the image.
The module also lets the test change the defaults. A test that wants the same user and database as the rest of this work sets them on the image before starting it.
let container = Postgres::default()
.with_db_name("ch19_tests")
.with_user("axumdocs")
.with_password("axumdocs")
.start()
.await
.unwrap();
The connection string then uses those values instead of the postgres defaults. The same idea applies to the image tag, which the with_tag call changes, and to init SQL, which the with_init_sql call registers to run when the container starts.
The Verified Equivalent Flow
The container commands were not run here, so the page does not claim they were. What was verified is the flow those commands feed. The same handler test that would run against the container was run against the local Postgres 16.15 server, with the same users table, the same migration, and the same connection string shape, and it passed.
use axum::{
Router,
body::Body,
http::{Request, StatusCode},
};
use axum_project::{app, db::setup_test_pool};
use serde_json::json;
use tower::ServiceExt;
const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";
async fn post_user(router: Router, name: &str, email: &str) -> (StatusCode, serde_json::Value) {
let response = router
.oneshot(
Request::builder()
.method("POST")
.uri("/users")
.header("content-type", "application/json")
.body(Body::from(
json!({ "name": name, "email": email }).to_string(),
))
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap())
}
#[tokio::test]
async fn docker_equivalent_flow_runs_against_local_postgres() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
sqlx::query("DELETE FROM users WHERE email = 't12-asha@example.com'")
.execute(&pool)
.await
.unwrap();
let router = app(pool);
let (status, body) = post_user(router, "Asha", "t12-asha@example.com").await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(body["name"], "Asha");
assert!(body["id"].as_i64().unwrap() > 0);
}
The test posts a user through the router and checks the 201 status, the name, and a positive id. It proves the handler, the pool, and the table work together. Against the container the only change is the connection string, with port 5433 instead of 5432, and the test code stays the same.
test docker_equivalent_flow_runs_against_local_postgres ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
The run above is real, against Postgres 16.15 on this machine. The container run is the same test with a different port, and the reader should expect the same pass on a machine with Docker.
The Flow Works:
If that test passes, the handler, the pool, and the table work together. The container changes only the server the test talks to, so the same pass on a machine with Docker means the container setup is right too.
How the Pieces Fit Together
The container flow and the local flow share everything except the server itself.
docker run postgres:16, or local Postgres server
|
v
Server listens, container on 5433, local on 5432
|
v
DATABASE_URL points at the server
|
v
setup_test_pool connects and runs migrations
|
v
Router test posts a user and checks the 201
|
v
Container stopped and removed, or local database kept
The test code never knows which server it talks to. That is the point of the connection string. The server is a detail the environment supplies, and the test only cares that the server answers and holds the right tables.
Common Beginner Mistakes
Connecting before the container is ready
// Wrong - the test runs in the same second as docker run
docker run -d postgres:16
cargo test
Postgres needs a few seconds to initialise, and a test that connects at once gets a refused connection. The fix is to wait for the "ready to accept connections" log line, or to let testcontainers wait for it, which the crate does by watching the container logs for the ready message before it returns the container.
Pointing at the wrong port
// Wrong - 5432 is the local server, the container is on 5433
const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";
A test that passes against the local server while the developer thinks it tests the container proves nothing about the container. The fix is to read the port in the connection string and match it to the -p mapping, and to stop the local server while testing the container, so a wrong port fails loudly instead of passing quietly.
Reusing a container with old data
docker run --name axum-test-db -e POSTGRES_DB=ch19_tests -d postgres:16
docker stop axum-test-db
docker start axum-test-db
The environment variables only take effect on a first start with an empty data directory. A restarted container keeps its old database, and a changed POSTGRES_DB value is ignored. The fix is to remove the container and start a fresh one when the settings change, or to use --rm so every start is fresh.
Dropping the testcontainers handle too early
// Wrong - the container is dropped before the query runs
let database_url = {
let container = Postgres::default().start().await.unwrap();
let port = container.get_host_port_ipv4(5432).await.unwrap();
format!("postgres://postgres:postgres@127.0.0.1:{port}/postgres")
};
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
The container value goes out of scope at the end of the block, and dropping it stops the container. The pool then connects to a port with nothing behind it. The fix is to keep the container in a variable that lives until the test ends, and to build the connection string from it without moving it into a smaller scope.
A Fixed Port Collides with a Running Server:
Mapping the container to host port 5432 while the local Postgres server runs fails, because the port is already taken. Docker reports the conflict and the container does not start. The fix is the mapped port 5433 from this page, or stopping the local server first. A random port from testcontainers never collides, which is one more reason the crate form is convenient.
Forgetting the container after the run
docker run --name axum-test-db -d postgres:16
# days later, the container still runs and still holds port 5433
A detached container runs until it is stopped, and a forgotten one holds its port and its memory. The next docker run with the same name fails, because the name is taken. The fix is docker ps to list running containers, and docker stop plus docker rm for the ones that are done. The --rm flag prevents the problem by removing the container on stop.
Final Complete Example
Everything on this page put together is one compose file, one container command, and the test that runs against whichever server the connection string names. The application code is unchanged from the last page, because the container changes the server, not the code.
services:
postgres:
image: postgres:16
container_name: axum-test-db
environment:
POSTGRES_PASSWORD: axumdocs
POSTGRES_USER: axumdocs
POSTGRES_DB: ch19_tests
ports:
- "5433:5432"
docker compose -f docker-compose.test.yml up -d
docker logs axum-test-db
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5433/ch19_tests" cargo test
docker compose -f docker-compose.test.yml down
The test file is the equivalent-flow test from above, run with the container port in the connection string. The testcontainers form is the alternative for a test that starts its own container, and it lives in the same tests/ folder.
use testcontainers_modules::{
postgres::Postgres, testcontainers::runners::AsyncRunner,
};
#[tokio::test]
async fn testcontainers_postgres_starts_a_container() {
let container = Postgres::default().start().await.unwrap();
let host = container.get_host().await.unwrap();
let port = container.get_host_port_ipv4(5432).await.unwrap();
let database_url = format!("postgres://postgres:postgres@{host}:{port}/postgres");
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
let (one,): (i32,) = sqlx::query_as("SELECT 1")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(one, 1);
}
On a machine with Docker, the compose flow and the testcontainers flow both end with the same passing test. On the machine these docs were written on, the local flow passed instead, and the Docker commands are presented from the official docs with that limit stated, not as runs that happened here.
Summary
A container turns the test database into a disposable object. The image fixes the Postgres version, the run command fixes the user and the database, and the stop command throws the whole thing away. The test code does not change, because the connection string carries the only difference, and that difference is a port number.
The decision framework is short. If every developer on the team has Docker, use a container, and use testcontainers when the test should start its own. If Docker is missing on any machine that runs the tests, keep the local server as the fallback, and keep the connection string as the one place where the choice lives. Either way, the habit that matters is the one from the last page. Read the connection string before running the tests, and make sure the port names the server the test is supposed to prove.