✦ For everyone, free.

Practical knowledge for real and everyday life

Home

6.2.3.3 Test Command Containers

A focused guide to Test Command Containers, connecting core concepts with practical Docker and container operations.

Test command containers run a project's automated test suite as a one-off container task, using exactly the same image (or a closely related build stage) that will eventually be deployed, ensuring tests run under conditions that closely mirror the actual production environment.

Running Tests in a One-Off Container

A test suite is executed as the container's command, with the container exiting based on whether the tests passed or failed.

docker run --rm myapp:test-stage npm test
Why Testing Inside a Container Catches Environment-Specific Issues

Running tests directly on a developer's local machine can miss issues specific to the actual deployment environment — a missing system dependency, a different library version — that only become apparent when tests run inside the same kind of container the application will actually be deployed in.

docker build --target test -t myapp:test .
docker run --rm myapp:test
Using the Test Container's Exit Code in CI

A CI pipeline relies directly on the test container's exit code to determine whether the test stage passed, gating subsequent pipeline steps on this result.

docker run --rm myapp:test
if [ $? -ne 0 ]; then
  echo "Tests failed"
  exit 1
fi
Passing Test-Specific Configuration

Test-specific environment variables or configuration can be supplied at run time, customizing test behavior (such as pointing to a test database) without needing a separate image built specifically for testing.

docker run --rm -e DATABASE_URL=postgres://test-db/test myapp:test
Why Test Command Containers Matter

Running a test suite as a one-off container task, using an environment closely matching production, provides meaningfully more confidence than running tests in a less representative local environment, while still benefiting from the disposability and automatic cleanup that one-off containers provide.