Test Automation Infrastructure
Docker for Test Environments
This course teaches QA engineers and testers how to use Docker to build test environments that are consistent, disposable, and easy to share across a team or a CI pipeline. You will learn core Docker concepts (images, containers, volumes, networks), how to write a Dockerfile for a test runner, and how to use Docker Compose to stand up a full stack, an application under test plus a database, a mock server, and a browser, with a single command. The course works through building images for Selenium and Playwright test runners, managing test data with volumes, isolating networks between parallel test runs, and wiring containerized tests into a continuous integration pipeline. By the end you will be able to replace flaky, hand-configured test machines with reproducible containers that any teammate, or any CI runner, can start from a clean state in minutes.
Intermediate · By the Xtest team · About 25 minutes to read
Introduction
Every tester has lived through the pain of 'it works on my machine but fails in CI', or a shared staging environment that five people quietly broke before a demo. Docker exists to remove that class of problem. A container packages an application, or a test runner, together with the exact operating system libraries, language runtime, and dependencies it needs, so it behaves the same way on a laptop, a colleague's laptop, and a CI server. For testing specifically, containers give you something precious: a throwaway environment. You can spin up a database, load it with known seed data, run your suite against it, and destroy it, all in a script, all in a minute or two, with zero risk of leftover state contaminating the next run. This course starts from first principles, what an image is, what a container is, how they differ from a virtual machine, and builds up to real, working setups: a Dockerfile that bakes in a Playwright or Selenium test runner, a Docker Compose file that brings up an application, its database, and a browser together, and a pattern for running that whole stack inside GitHub Actions, GitLab CI, Jenkins, or CircleCI. Along the way you will learn the habits that keep containerized test environments fast and reliable: keeping images small, using volumes correctly for test data, giving each parallel run its own isolated network, and tearing everything down cleanly after a run. No prior Docker experience is assumed, but comfort with the command line and with running an automated test suite (in any framework) will help.
Why Containerize Test Environments, and Core Docker Concepts
The case for containers in testing
Before touching a single Docker command, it helps to understand the problem containers solve. A typical test environment accumulates small differences over time: a different library version, a leftover row in a database, an environment variable someone set six months ago and forgot about. Each difference is small, but together they make a test environment unreliable, a test that passes locally but fails in CI, or passes in CI but fails for a new hire, is usually a symptom of environment drift rather than a real bug.
Docker fixes this by making the environment itself part of version control. A Dockerfile is a plain text recipe: start from a known base image, install exact versions of exact packages, copy in your test code, and define how to run it. Anyone, or any machine, that builds that Dockerfile gets byte-for-byte the same environment. There is no 'works on my machine', because the image is the machine, in the relevant sense.
Images, containers, volumes, and networks
Four concepts carry almost all of the weight in day-to-day use:
- Image: a read-only template, built from a Dockerfile, containing an operating system layer, a runtime (Node.js, Python, a JDK), and your code.
- Container: a running instance of an image. You can start several containers from the same image, each isolated from the others.
- Volume: a way to persist or share data outside a container's own filesystem, useful for test data that should survive a container restart, or for sharing test reports back to the host machine.
- Network: a private network Docker creates so containers can talk to each other by name, for example a test runner container reaching an application container at the hostname
apprather than a hardcoded IP address.
Understanding these four well is enough to design almost any test environment: an image per service, containers started fresh for each test run, a volume for the data that needs to persist, and a network scoped to that run so parallel runs never interfere with each other.
How this differs from a virtual machine
A virtual machine virtualizes an entire computer, including its own kernel, and typically takes tens of seconds or minutes to boot. A container shares the host machine's kernel and only packages the application layer, so it starts in a second or two and uses a fraction of the disk space. For testing, this difference matters enormously: the practical, repeatable habit of tearing a whole environment down and rebuilding it before every test run is only realistic because containers are fast and cheap to create and destroy.
The Problem with Shared and Hand-Configured Test Environments
Before containers, most teams tested against one of two kinds of environment: a shared staging server, or each engineer's own locally installed copy of the application and its dependencies. Both have the same underlying flaw: they are long-lived, mutable, and nobody fully controls what state they are in at any given moment.
A shared staging server accumulates test data from everyone who has ever run a test against it. A test that checks 'there are 3 orders for this user' quietly becomes flaky the day two people run their suites at the same time, because now there are 5 orders, or the other person's run deleted the user entirely. A locally installed environment drifts in the opposite way: one developer upgrades a database driver to fix an unrelated bug, and now a test that passed yesterday fails today, for a reason that has nothing to do with the code under test.
Both problems share a root cause: the environment is not reproducible on demand. Containers solve this by treating the environment as disposable. Instead of nursing one long-lived staging server, you define, in a Dockerfile and a Compose file, exactly what 'a correct test environment' looks like, and you create a fresh one, with known starting data, every time you need to run a suite. When the run finishes, you throw the containers away. The next run starts from the same clean definition, not from whatever state the last run happened to leave behind. This single change, from a long-lived environment to a disposable one, removes an entire category of test flakiness that has nothing to do with the quality of the tests themselves.
Core Docker Concepts for Testers: Images, Containers, Volumes, Networks
You do not need to know everything about Docker to use it well for testing, but four concepts are worth knowing cold.
An image is built once, from a Dockerfile, and is immutable: it never changes after it is built. Think of it as a recipe plus its finished, frozen output. A container is what you get when you tell Docker to run that image; it is a live, writable instance, and you can run many containers from one image at once, each with its own filesystem changes and its own process, fully isolated from the others. This is exactly the property you want for parallel test runs: ten containers from the same test-runner image can execute ten independent suites at the same time without stepping on each other.
A volume solves the problem that a container's own filesystem disappears when the container is removed. If a test needs a seeded database that should persist across a container restart, or if you want test reports and screenshots written inside the container to land on the host machine where a CI system can pick them up, you mount a volume for that specific path.
A network is what lets containers find each other. By default, Docker Compose puts every service defined in one docker-compose.yml file on the same private network, and each service is reachable by the name given to it in that file. A test container can therefore point its configuration at http://app:3000 instead of a brittle, environment-specific IP address or hostname, and that same configuration works identically on every machine that runs the Compose file.
# Dockerfile for a Playwright test runner
FROM mcr.microsoft.com/playwright:v1.46.0-jammy
WORKDIR /tests
# Install exact dependency versions from the lock file
COPY package.json package-lock.json ./
RUN npm ci
# Copy in the test code itself
COPY tests/ ./tests/
COPY playwright.config.ts ./
# Run the suite when the container starts
CMD ["npx", "playwright", "test", "--reporter=line"]
A Dockerfile that builds a self-contained image for running a Playwright suite, with Node.js, the Playwright browsers, and the project's exact npm dependencies already baked in.
# Build the image
docker build -t my-app-tests:latest .
# Run it once, mounting a folder so the HTML report lands on the host
docker run --rm \
-v "$(pwd)/playwright-report:/tests/playwright-report" \
my-app-tests:latest
# Clean up any stopped containers and dangling images afterwards
docker image prune -f
Building the test image, running it as a disposable container (--rm removes it as soon as it exits), and mounting a volume so the test report survives after the container is gone.
Tips
- Pin exact versions in your Dockerfile (a specific base image tag, a lock file for dependencies) so a rebuild six months from now produces the same environment, not whatever the latest versions happen to be on that day.
- Always run test containers with --rm, or remove them explicitly after the run, so a failed run does not leave stopped containers slowly filling up disk space on the CI runner or your laptop.
- Give every parallel test run its own Docker network (Compose does this automatically per project) so two suites running at the same time never see each other's containers or data.
Common pitfalls
- Using the `latest` tag for a base image. This silently changes what you get every time you rebuild, undoing the whole point of reproducibility; pin a specific version tag instead.
- Forgetting that a container's filesystem is wiped when the container is removed, then wondering why test reports or screenshots written inside the container never make it to disk. Mount a volume for any path you need to keep.
- Building a huge image by installing a full desktop environment or unnecessary tools just because a tutorial did, which slows down every build and every CI run; start from a minimal, purpose-built base image (like an official language or test-framework image) and add only what the tests need.
Building Test Images with Dockerfiles
A test image is a Dockerfile that produces exactly the environment your test suite needs and nothing more. The goal is a container that any CI runner can pull and run without first installing a browser, a driver, a language runtime or a testing library. Getting there well means thinking about four things together: which base image to start from, how to keep the final image small, how to make rebuilds fast when only test code changes, and how to bake in browsers and drivers so the image is self-contained.
Start from a base image built for the job rather than a bare OS image. The official Playwright images already ship with Chromium, Firefox and WebKit plus the OS libraries each needs, and Selenium's standalone images ship a browser and a matching driver behind a Selenium Server. Starting from one of these saves you from hunting down the dozens of system packages a headless browser actually needs to render a page.
From there, the Dockerfile should separate concerns: install dependencies in one layer, copy test code in another, and run tests as the last step (or leave that to docker run so the image stays reusable). Multi-stage builds let you compile or bundle in one stage and copy only the finished artifacts into a lean final stage, which keeps the image you actually ship small and fast to pull in CI.
Choosing and Layering a Base Image
Picking the right base image is the single decision that affects everything downstream. For a Playwright suite, starting from an official Playwright base image means browsers and their OS-level dependencies (fonts, codecs, sandboxing libraries) are already present and version-matched to the Playwright package you install, which avoids the classic mismatch where the library expects a browser build the image doesn't have. For Selenium, a standalone browser image gives you a running Selenium Server and browser combination, while a 'node' image without a hub expects to be wired into a Selenium Grid.
Once a base is chosen, order your Dockerfile instructions from least to most frequently changing. System packages and language runtimes change rarely, so install them first. Dependency manifests (package.json, requirements.txt) and their install step come next. Your actual test code, which changes on every commit, should be copied last. Docker's layer cache reuses every layer up to the first one that changed, so this ordering means a developer who only edits a spec file gets a rebuild that reuses every cached layer except the final copy.
Avoid installing browsers yourself on top of a generic base unless you have a specific reason to; version drift between a manually installed browser and the driver your test library expects is a frequent and hard-to-diagnose source of flaky CI runs.
Multi-Stage Builds and Dependency Caching
A multi-stage Dockerfile uses more than one FROM instruction, with each stage able to copy specific files from an earlier one. This matters for test images because a build stage often needs compilers, type-checkers or bundlers that have no place in the image that actually runs tests. Separating 'build' from 'test' keeps the final image focused on runtime dependencies only: the browser, the driver, the test runner and the compiled or bundled test code.
Caching dependency installs is the other half of a fast feedback loop. Docker caches a layer as long as the instruction and the files it depends on are unchanged, so copying only the dependency manifest before running the install command, and copying the rest of the source afterward, means an unrelated code change does not force a full reinstall of every package. For Node-based suites this means copying package.json and a lockfile, running npm ci, and only then copying the test files. For Python suites the same pattern applies to requirements.txt and pip install.
A common refinement is a .dockerignore file that excludes node_modules, local virtual environments, and report or screenshot output directories from the build context, since sending those to the Docker daemon on every build slows things down for no benefit and can accidentally bake stale artifacts into the image.
# Stage 1: install dependencies and run a build/compile step if needed
FROM mcr.microsoft.com/playwright:v1.46.0-jammy AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx tsc -p tsconfig.json
# Stage 2: lean final image with only what's needed to run tests
FROM mcr.microsoft.com/playwright:v1.46.0-jammy
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY playwright.config.ts ./
CMD ["npx", "playwright", "test"]
A multi-stage Dockerfile for a Playwright suite: the first stage installs dependencies and compiles TypeScript test files, and the second stage copies only the compiled output and node_modules into a fresh image, keeping the final image free of build-only tooling.
# Build the image, then run it against a target URL passed as an env var
docker build -t my-test-suite:latest .
docker run --rm -e BASE_URL=https://staging.example.com my-test-suite:latest
Builds the test image once and runs it with an environment variable that points the suite at whichever environment should be tested, so the same image works across staging, QA or any other target without rebuilding.
Tips
- Pin exact versions for your base image and your test library (for example a specific Playwright image tag matched to the exact Playwright npm version) so a CI run next month uses the same browser build as the one that passed today.
- Put a `.dockerignore` file next to your Dockerfile and exclude `node_modules`, `.git`, and any local report or trace output directories to keep build context small and rebuilds fast.
- Run tests as a non-root user inside the container where your base image supports it; several official browser images already set this up, and it avoids permission surprises when the container writes report files to a mounted volume.
Common pitfalls
- Installing a browser or driver manually on a generic base image instead of starting from one built for the purpose: version mismatches between the browser and the driver are a common cause of tests that fail only in CI and nowhere else.
- Copying the entire project directory before running the dependency install step: this busts Docker's layer cache on every source change and turns a one-line test edit into a full dependency reinstall on every build.
Orchestrating Multi-Service Test Stacks with Docker Compose
A single containerized application is rarely enough for realistic end-to-end testing. Most real systems depend on a database, one or more third-party APIs, caches, and message queues, and your test environment needs to reproduce that topology reliably every time a build runs. Docker Compose solves this by letting you describe an entire stack, application, database, mock API, and test runner, as one declarative file that can be brought up and torn down as a unit.
The goal of a good Compose-based test stack is reproducibility: anyone, on any machine, running docker compose up should get byte-for-byte the same environment as CI does. That means pinning image versions, avoiding host-machine assumptions (no localhost ports that happen to be free, no files mounted from a developer's home directory), and making the stack start from a known, empty state every time.
This section covers three practical concerns that trip up most teams the first time they try this: waiting for dependent services to actually be ready before running tests (not just started), seeding deterministic test data into the database before the test runner begins, and making sure the stack is torn down completely, including volumes, even when a test run crashes or times out. We'll also look at wiring the same Compose file into GitHub Actions, GitLab CI, Jenkins, and CircleCI so that every build gets an isolated, disposable copy of the stack rather than sharing a long-lived staging environment that tests can quietly corrupt.
Treating your test environment as code, versioned alongside the application in the same repository, is the core idea here: the Compose file becomes a contract that describes exactly what "the environment under test" means, and it travels with every commit.
Health Checks and Startup Ordering
Compose's depends_on only controls the order containers are started in, not whether the service inside is ready to accept traffic. A database container can report as running long before PostgreSQL has finished initializing, and a mock API container can be listening on its port before it has loaded its stubbed responses. Running your test suite against a stack that looks up but isn't ready produces flaky, non-deterministic failures that waste far more time than they save.
The fix is to define a healthcheck for every service your tests depend on, and to use depends_on with the condition: service_healthy form so Compose genuinely waits. For a database, the healthcheck is usually a lightweight native client call (pg_isready for PostgreSQL, mysqladmin ping for MySQL). For an HTTP-based mock API or your application itself, a curl or wget against a /health endpoint works well, as long as that endpoint doesn't just return 200 unconditionally but actually checks its own dependencies.
Set realistic interval, timeout, retries, and start_period values; a database can legitimately take several seconds to come up on a cold container, and a health check that gives up too early will fail builds for no real reason. It's also worth giving the test-runner service itself a depends_on on every other service's healthy state, so the test command never executes until the entire stack is confirmed ready, removing the need for ad hoc sleep statements in CI scripts.
Seeding Data and Clean Teardown
Tests need predictable data to assert against, and the cleanest way to get it in a container-based stack is a dedicated seeding step rather than baking fixtures into the application image. A common pattern is a short-lived seed service in the Compose file that runs a script against the database once it is healthy, inserts the fixtures the test suite expects, and then exits; the test runner's depends_on waits on this seed service completing successfully, not just the database being up.
Keep seed data minimal and purpose-built for the scenarios under test rather than copying a slice of production data, which drifts out of sync and can include data you don't want in a disposable environment. Each test run should start from the same seed, so avoid tests that mutate shared fixtures in ways that affect other tests in the same run; prefer unique identifiers per test where possible.
Teardown deserves the same care as startup. docker compose down --volumes --remove-orphans should run unconditionally at the end of a CI job, in a step that executes even if the test step fails, otherwise a crashed run leaves behind containers, networks, and named volumes that silently consume disk and can leak state into the next run if names collide. Using docker compose -p with a unique project name per CI job (for example, the build ID) avoids two concurrent builds colliding on the same container and network names, which is essential once more than one pipeline can run at a time on shared CI infrastructure.
version: "3.9"
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: test
POSTGRES_DB: appdb
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 10
mock-api:
image: wiremock/wiremock:3.5.4
volumes:
- ./mocks:/home/wiremock/mappings
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:8080/__admin/health"]
interval: 5s
retries: 10
app:
build: .
depends_on:
db:
condition: service_healthy
mock-api:
condition: service_healthy
environment:
DATABASE_URL: postgres://postgres:test@db:5432/appdb
THIRD_PARTY_URL: http://mock-api:8080
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 5s
retries: 10
seed:
build: ./seed
depends_on:
db:
condition: service_healthy
environment:
DATABASE_URL: postgres://postgres:test@db:5432/appdb
tests:
build: ./e2e
depends_on:
app:
condition: service_healthy
seed:
condition: service_completed_successfully
environment:
BASE_URL: http://app:3000
command: npx playwright test
A complete Compose file with database, mocked third-party API (WireMock), application, a one-shot seed step, and a Playwright test runner, all gated by health checks so tests never start against a half-ready stack.
#!/usr/bin/env bash
set -euo pipefail
PROJECT="ci-${CI_JOB_ID:-local}"
trap 'docker compose -p "$PROJECT" down --volumes --remove-orphans' EXIT
docker compose -p "$PROJECT" up --build --abort-on-container-exit --exit-code-from tests tests
A CI-friendly runner script that gives each build a unique Compose project name to avoid collisions, runs the stack until the tests container exits, and guarantees teardown (including volumes) via a trap even if the tests fail or the script is interrupted.
Tips
- Pin every image tag (database, mock API, base images) to a specific version; letting any service float on `latest` will eventually break a build with no code change to blame.
- Use `service_completed_successfully` as a `depends_on` condition for one-shot setup containers like seeders, rather than a plain `depends_on` that only waits for the container to start.
- Give each CI job its own Compose project name (`-p`) so parallel builds never share networks, volumes, or container names on the same runner.
- Write health check endpoints that verify real readiness (a database connection, a loaded config) rather than returning a static 200, or the health check gives you false confidence.
Common pitfalls
- Relying on `depends_on` alone for startup ordering: without a `healthcheck` and `condition: service_healthy`, Compose only waits for the container process to start, not for the service inside it to be ready, which causes intermittent failures that look like flaky tests but are really race conditions.
- Forgetting to tear down on failure: if `docker compose down --volumes` only runs on a successful test step, a failed or cancelled CI job leaves containers, networks, and volumes behind, which can silently corrupt or slow down the next build on shared infrastructure.
Exercises
Exercise 1: Containerize a Test Runner
In this exercise you will take an existing automated test suite (any framework, Playwright, Selenium, or Jest, is fine) and package it into a Docker image so that it runs identically on your machine and on any other machine with Docker installed. The goal is to experience, hands-on, the difference between 'my tests pass on my machine' and 'my tests pass inside a container anyone can run'. You will write a Dockerfile from scratch, choosing an appropriate base image, installing exact dependency versions, and copying in only the files the test run actually needs. You will then build the image, run it as a disposable container, and confirm that a test report is correctly written back to your host machine through a mounted volume. Finally, you will deliberately break something inside the container (for example, by changing a dependency version in the Dockerfile) to see how the image rebuild makes the change explicit and reviewable, unlike a silent local environment change.
- Pick an existing small test suite, or write 3 to 5 simple tests against a public site using Playwright or Selenium.
- Write a Dockerfile that starts from an appropriate base image, installs dependencies with a lock file, and copies in the test code.
- Build the image with `docker build -t test-runner .` and fix any errors that come up.
- Run the image with `docker run --rm` and confirm the tests execute and report their results in the terminal.
- Add a volume mount so the HTML or JSON test report is written to a folder on your host machine.
- Change one dependency version in the Dockerfile, rebuild, and observe how the change is now visible and reviewable in the Dockerfile itself rather than hidden in a local install.
Expected outcome: A working Dockerfile and image that runs the chosen test suite identically regardless of which machine it is built and run on, with a test report correctly persisted to the host filesystem after the container exits.
Exercise 2: Multi-Container Test Stack with Docker Compose
Building on Exercise 1, you will now use Docker Compose to bring up a small multi-service test environment: an application container, a database container, and your test-runner container, all on one private network, started and stopped with a single command. This exercise focuses on the orchestration skills needed for realistic test environments, where the system under test is rarely a single container. You will configure the test runner to reach the application by its service name rather than a hardcoded address, seed the database with known starting data before the tests run, and ensure the whole stack is torn down cleanly afterward, leaving no leftover containers or data for the next run.
- Write a docker-compose.yml defining three services: app, db, and tests.
- Configure the tests service to depend on app and db, and to reach the app by its Compose service name.
- Add a startup script or health check so tests wait until the app is actually ready before starting.
- Seed the db service with known test data using an initialization script.
- Run `docker compose up --abort-on-container-exit` and confirm the tests run against the freshly seeded stack.
- Run `docker compose down -v` and confirm all containers, networks, and volumes are removed cleanly.
Expected outcome: A single docker-compose.yml file that, with one command, builds and starts an application, a database, and a test runner, runs the full suite against known seed data, and tears everything down afterward with no leftover state.
Quiz
1. What is the main reason containerized test environments reduce flaky tests compared to a shared staging server?
- Containers run tests faster than any other method
- Containers are disposable and can be rebuilt from a known definition for every run, removing leftover state from previous runs
- Containers automatically fix bugs in the application under test
- Containers eliminate the need to write assertions in tests
Show answer
B. Containers are disposable and can be rebuilt from a known definition for every run, removing leftover state from previous runs
A shared, long-lived environment accumulates state from every previous run, which causes flakiness unrelated to the code under test. Because containers are cheap and fast to create and destroy, you can start every test run from a known, clean definition, removing that source of flakiness.
2. In Docker terminology, what is the relationship between an image and a container?
- An image and a container are the same thing, just different names
- A container is a read-only template; an image is a running instance of it
- An image is a read-only template; a container is a running, writable instance created from that image
- A container is built from a Dockerfile; an image is created at runtime with no Dockerfile needed
Show answer
C. An image is a read-only template; a container is a running, writable instance created from that image
An image is the immutable template built from a Dockerfile. A container is what you get when you run that image, a live, writable instance. Many containers can be started from the same image, each isolated from the others.
3. Why should a Dockerfile for a test environment avoid using the `latest` tag for its base image?
- The `latest` tag is always slower to download
- Using `latest` means the exact contents of the base image can change between builds, breaking reproducibility
- Docker does not allow the `latest` tag to be used in test environments
- The `latest` tag only works with Windows containers
Show answer
B. Using `latest` means the exact contents of the base image can change between builds, breaking reproducibility
The whole point of containerizing a test environment is reproducibility: the same Dockerfile should produce the same environment every time it is built. The `latest` tag points to whatever the newest version is at build time, which can silently change and undermine that reproducibility. Pinning a specific version tag avoids this.
4. In a Docker Compose file defining an app service and a tests service, how should the tests service typically reach the app service?
- By the app container's randomly assigned IP address
- By the hostname 'localhost', since all containers share the host's network
- By the service name given to it in the docker-compose.yml file, since Compose puts services on a shared private network
- It cannot reach it at all without exposing a port to the public internet
Show answer
C. By the service name given to it in the docker-compose.yml file, since Compose puts services on a shared private network
Docker Compose automatically creates a private network for the services defined in a Compose file, and each service is reachable by the name it is given in that file. This means a test container can reliably reach `http://app:3000` regardless of which machine the stack is run on.
5. Why is a volume useful when running a test suite inside a disposable container?
- A volume speeds up the container's CPU
- A volume lets data such as test reports or screenshots survive and be written to the host machine, since a container's own filesystem is removed along with the container
- A volume is required for a container to start at all
- A volume replaces the need for a Dockerfile
Show answer
B. A volume lets data such as test reports or screenshots survive and be written to the host machine, since a container's own filesystem is removed along with the container
When a disposable container is removed (for example, after running with --rm), anything written only to its own filesystem is lost. Mounting a volume for a specific path, such as a test-report folder, ensures that data is written to the host machine and survives after the container is gone.