13.1.2 Docker Test Execution
A focused guide to Docker Test Execution, connecting core concepts with practical Docker and container operations.
Docker test execution runs an application's test suite within a containerized environment as part of CI, ensuring tests run against exactly the same runtime environment the application will actually use, rather than whatever happens to be available on the CI runner's own host.
Running Tests Directly Against the Built Image
The most direct approach runs the test suite as a command within the actual application image.
docker build -t myapp:test .
docker run --rm myapp:test npm test
This runs tests within the exact same environment the application's production image provides, rather than a potentially different environment on the bare CI runner.
Running Tests Within a Dedicated Test Stage
A multi-stage Dockerfile can include a stage specifically intended for running tests, distinct from the final production stage.
FROM node:20-alpine AS test
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm test
FROM node:20-alpine AS production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
docker build --target test -t myapp:test .
This explicitly builds and runs just the test stage, separate from constructing the final production image.
Why Running Tests in a Container Specifically Matters
Without this approach, tests might pass against a CI runner's own environment but fail (or behave differently) once actually run within the application's real container — testing directly within the container catches this kind of environment-specific discrepancy before it reaches production.
docker run --rm myapp:test npm test
Capturing Test Results From a Container Run
Test results or coverage reports generated inside the container can be extracted for further processing or reporting.
docker run --rm -v $(pwd)/test-results:/app/test-results myapp:test npm test
Why Docker Test Execution Matters
Running tests directly within the application's actual containerized environment provides considerably stronger assurance that passing tests genuinely reflect how the application will behave once deployed, compared to testing against a potentially different bare CI runner environment.