QA and Test Automation · Lab 24 of 35

Run Your Tests Inside Docker With Compose: Hands-On Lab

Run ShopRung, the pytest API suite and the Playwright suite in containers with Docker Compose: a health-checked app, test containers that reach it by service name, a pinned Playwright image, practice bugs through an environment variable, exit codes for CI, and clean teardown.

⏱ 60 minIntermediate💸 Free6 steps

Docker Desktop or Docker EngineDocker Compose v2python:3.12-slimmcr.microsoft.com/playwright:v1.63.0-nobleShopRung

Overview video

1 / 6

0 of 6 steps done

What you will build

One file, compose.test.yaml, that runs the whole test setup on any machine with Docker, with nothing else installed:

  • shoprung, built from ShopRung's own Dockerfile, with a health check, and practice bugs switched by the SHOPRUNG_BUGS environment variable.
  • api-tests: the pytest suite from lab 11 in the official Python image, 23 passed.
  • e2e: the Playwright suite from lab 13 in the official Playwright image (browsers included), 7 passed.
  • Commands that start the app only when it is healthy, return the tests' exit code, and remove everything afterwards, plus a GitHub Actions job that runs the same file.

Before you start

  • The episode behind it: Docker for testers.
  • The shoprung-qa folder from Suites in GitHub Actions: shoprung/, api-tests/ (lab 11) and e2e/ (lab 13, with its package-lock.json).
  • Docker: Docker Desktop on Mac or Windows, or Docker Engine with the Compose plugin on Linux.

Setup

S1Check Docker and Compose

Start Docker Desktop (or the Docker service on Linux), then check both commands answer. Compose v2 is the docker compose subcommand, with a space.

Run
docker version --format "{{.Server.Version}}"
docker compose version
You should seeyour text will differ: the model writes it
28.5.1
Docker Compose version v2...

S2Open the project folder

Work in shoprung-qa. Stop any ShopRung you started with npm start: in this lab, ShopRung runs in a container instead.

Run
cd shoprung-qa
ls
You should see
api-tests  e2e  shoprung
1

ShopRung in a container, healthy

Build the app from its Dockerfile and let Docker check it is really up.

ShopRung ships a Dockerfile (shown here, do not change it): a small Node 24 image, the code copied in, port 8080. Create compose.test.yaml in shoprung-qa with one service, shoprung, built from that folder.

The healthcheck asks ShopRung's health endpoint every 2 seconds from inside the container. Docker marks the container healthy only when it answers, and the test containers in the next steps will wait for exactly that. SHOPRUNG_BUGS: ${SHOPRUNG_BUGS:-} passes your shell's variable through, empty by default.

Start it in the background and look at its status.

compose.test.yaml
# ShopRung and its test suites, each in its own container, on one private network.
#   docker compose -f compose.test.yaml up -d shoprung
#   docker compose -f compose.test.yaml down -v
services:
  shoprung:
    build: ./shoprung
    environment:
      SHOPRUNG_BUGS: ${SHOPRUNG_BUGS:-}
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:8080/api/health"]
      interval: 2s
      timeout: 3s
      retries: 15
  1. Builds an image from shoprung/Dockerfile the first time.line 6
  2. The Alpine image has BusyBox wget, which sends a GET: ShopRung does not answer HEAD.line 10
  3. Up to 30 seconds to become healthy before Docker calls it unhealthy.line 13
shoprung/Dockerfile
# ShopRung has no dependencies to install: it only needs Node.js.
FROM node:24-alpine
WORKDIR /app
COPY package.json ./
COPY src ./src
COPY public ./public
ENV PORT=8080
EXPOSE 8080
CMD ["node", "--disable-warning=ExperimentalWarning", "src/server.js"]
Run
docker compose -f compose.test.yaml up -d shoprung
docker compose -f compose.test.yaml ps
You should seeyour text will differ: the model writes it
NAME                IMAGE             COMMAND                  SERVICE    CREATED         STATUS                   PORTS
docker-shoprung-1   docker-shoprung   "docker-entrypoint.s…"   shoprung   9 seconds ago   Up 8 seconds (healthy)   8080/tcp
Stuck on this step?
Status stays at "(health: starting)" and then "unhealthy".
Read the app's output with docker compose -f compose.test.yaml logs shoprung. A typo in the health URL is the usual cause.
2

The API suite in a Python container

23 API tests run in a container that reaches ShopRung by its service name.

Add the api-tests service. It uses the official python:3.12-slim image, mounts your api-tests folder at /tests, installs the requirements and runs pytest. Nothing is installed on your machine.

Two lines matter most. depends_on with condition: service_healthy starts ShopRung first and waits until its health check passes: no sleeps. BASE_URL: http://shoprung:8080: inside the Compose network, localhost would be the test container itself; the service name shoprung is the host name of the app. Lab 11's suite already reads BASE_URL.

docker compose run --rm api-tests runs the service once, prints its output, removes the container afterwards, and exits with the tests' exit code.

compose.test.yaml 11 new or changed lines
# ShopRung and its test suites, each in its own container, on one private network.
#   docker compose -f compose.test.yaml run --rm api-tests
#   docker compose -f compose.test.yaml down -v
services:
  shoprung:
    build: ./shoprung
    environment:
      SHOPRUNG_BUGS: ${SHOPRUNG_BUGS:-}
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:8080/api/health"]
      interval: 2s
      timeout: 3s
      retries: 15

  api-tests:
    image: python:3.12-slim
    depends_on:
      shoprung:
        condition: service_healthy
    environment:
      BASE_URL: http://shoprung:8080
    working_dir: /tests
    volumes:
      - ./api-tests:/tests
    command: sh -c "pip install -q --root-user-action=ignore -r requirements.txt && pytest -p no:cacheprovider --junitxml=results/api.xml"
  1. Wait for the health check, not just for the container to start.line 19
  2. The service name is the host name on the Compose network.line 21
  3. Your folder inside the container: results/api.xml appears on your machine too.line 24
  4. Keeps pytest from writing a .pytest_cache folder into your project.line 25
Run
docker compose -f compose.test.yaml run --rm api-tests
echo "exit code: $?"
You should seeyour text will differ: the model writes it
 Container docker-shoprung-1  Running
============================= test session starts ==============================
platform linux -- Python 3.12.16, pytest-8.3.4, pluggy-1.7.0
rootdir: /tests
configfile: pytest.ini
collected 23 items

tests/test_auth.py ......                                                [ 26%]
tests/test_cart.py ..........                                            [ 69%]
tests/test_orders.py .....                                               [ 91%]
tests/test_schema.py ..                                                  [100%]

------------------ generated xml file: /tests/results/api.xml ------------------
============================== 23 passed in 0.76s ==============================
exit code: 0
Stuck on this step?
ConnectError or "ShopRung is not running at http://localhost:8080".
BASE_URL is missing or says localhost. It must be http://shoprung:8080 inside Compose.
3

The UI suite in the Playwright image

7 browser tests in Microsoft's Playwright image, browsers and system libraries included.

Add the e2e service. The official image mcr.microsoft.com/playwright:v1.63.0-noble already contains Chromium, Firefox and WebKit with every Linux library they need. Pin the tag to the same version as @playwright/test in e2e/package.json (1.63.0): each Playwright release expects its own browser builds.

The second volume line, /e2e/node_modules, is an anonymous volume: it gives the container its own node_modules, so npm ci inside Linux never overwrites the one on your Mac or Windows machine, whose binaries would not work in Linux anyway. CI: "true" turns on the retries from lab 13's config.

compose.test.yaml 8 new or changed lines
# ShopRung and its test suites, each in its own container, on one private network.
#   docker compose -f compose.test.yaml run --rm api-tests
#   docker compose -f compose.test.yaml run --rm e2e
#   docker compose -f compose.test.yaml down -v
services:
  shoprung:
    build: ./shoprung
    environment:
      SHOPRUNG_BUGS: ${SHOPRUNG_BUGS:-}
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:8080/api/health"]
      interval: 2s
      timeout: 3s
      retries: 15

  api-tests:
    image: python:3.12-slim
    depends_on:
      shoprung:
        condition: service_healthy
    environment:
      BASE_URL: http://shoprung:8080
    working_dir: /tests
    volumes:
      - ./api-tests:/tests
    command: sh -c "pip install -q --root-user-action=ignore -r requirements.txt && pytest -p no:cacheprovider --junitxml=results/api.xml"

  e2e:
    image: mcr.microsoft.com/playwright:v1.63.0-noble
    depends_on:
      shoprung:
        condition: service_healthy
    environment:
      BASE_URL: http://shoprung:8080
      CI: "true"
    working_dir: /e2e
    volumes:
      - ./e2e:/e2e
      - /e2e/node_modules
    command: sh -c "npm ci --no-audit --no-fund && npx playwright test"
  1. Same version as the project: a mismatch fails with "Executable doesn't exist".line 29
  2. The container's own node_modules, never mixed with your machine's.line 39
  3. A clean, locked install from package-lock.json on every run.line 40
Run
docker compose -f compose.test.yaml run --rm e2e
You should seeyour text will differ: the model writes it
 Container docker-shoprung-1  Running

added 3 packages in 426ms

Running 7 tests using 1 worker

  ✓  1 [setup] › tests/auth.setup.ts:4:6 › log in as alice (153ms)
  ✓  2 [chromium] › tests/cart.spec.ts:3:5 › SAVE10 at exactly $50.00 gives a total of $49.99 (305ms)
  ✓  3 [chromium] › tests/cart.spec.ts:16:5 › shipping is free from $75.00 (176ms)
  ✓  4 [chromium] › tests/checkout.spec.ts:3:5 › placing an order shows it as PLACED and empties the cart (228ms)
  ✓  5 [chromium] › tests/search.spec.ts:3:5 › search finds the two mugs (142ms)
  ✓  6 [chromium] › tests/search.spec.ts:9:5 › search is not case sensitive (132ms)
  ✓  7 [chromium] › tests/search.spec.ts:14:5 › the out of stock mug cannot be added (128ms)

  7 passed (1.8s)
Stuck on this step?
The first run takes minutes.
Docker is downloading the Playwright image (about 2 GB). Later runs reuse it and start in seconds.
4

Practice bugs and a fresh start

Start ShopRung with a bug, see one test fail, then remove everything.

Containers make a clean start easy. down -v stops and removes the containers, the network and any volumes, so the next run starts from ShopRung's seed data. Then start the API suite with SHOPRUNG_BUGS=coupon-boundary: Compose passes it to ShopRung, which starts with that bug on.

Exactly one test fails, and docker compose run exits with 1. That exit code is what makes a CI job red.

Run
docker compose -f compose.test.yaml down -v
SHOPRUNG_BUGS=coupon-boundary docker compose -f compose.test.yaml run --rm api-tests
echo "exit code: $?"
docker compose -f compose.test.yaml down -v
You should seeyour text will differ: the model writes it
tests/test_cart.py .....F....                                            [ 69%]
...
>       assert r.status_code == 200
E       assert 400 == 200
...
FAILED tests/test_cart.py::test_save10_applies_at_exactly_50_dollars - assert...
========================= 1 failed, 22 passed in 0.83s =========================
exit code: 1
Stuck on this step?
The bug does not switch on.
ShopRung reads SHOPRUNG_BUGS only when it starts. Run down -v first, so the next command starts a new ShopRung container.
5

The same file in CI

A GitHub Actions job that needs only Docker.

GitHub's Ubuntu machines have Docker and Compose installed, so the workflow is short: no Node, Python or browser setup steps at all. Every developer, tester and CI machine runs the same images.

The last steps always run: they save ShopRung's log from the container, upload the results, and remove everything. Add the file next to lab 23's workflow, check it with actionlint, and push.

.github/workflows/docker-tests.yml
name: docker-tests

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  tests:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4

      - name: API tests in Docker
        run: docker compose -f compose.test.yaml run --rm api-tests

      - name: UI tests in Docker
        run: docker compose -f compose.test.yaml run --rm e2e

      - name: Keep results and the shop's log
        if: always()
        run: docker compose -f compose.test.yaml logs shoprung > shoprung.log

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: docker-test-results
          path: |
            api-tests/results/
            e2e/playwright-report/
            e2e/test-results/
            shoprung.log

      - name: Stop and remove everything
        if: always()
        run: docker compose -f compose.test.yaml down -v
  1. Fails the step when a test fails: run passes on the exit code.line 19
  2. The app's own output, saved before the containers are removed.line 26
  3. Leave nothing behind, even after a failure.line 40
Run
actionlint
git add compose.test.yaml .github/workflows/docker-tests.yml
git commit -m "Tests in Docker" && git push
You should seeyour text will differ: the model writes it
docker-tests ✓
  API tests in Docker ✓   UI tests in Docker ✓
6

Look inside a running container

The commands you use when something in a container misbehaves.

Start ShopRung on its own again and try the everyday commands: ps for status and health, logs for the app's output (every request is logged), and exec to run a command inside the container, here the same health request Docker's check makes. Finish with down -v.

Run
docker compose -f compose.test.yaml up -d shoprung
docker compose -f compose.test.yaml ps
docker compose -f compose.test.yaml exec shoprung wget -qO- http://localhost:8080/api/health
docker compose -f compose.test.yaml logs --tail 5 shoprung
docker compose -f compose.test.yaml down -v
You should seeyour text will differ: the model writes it
... Up 8 seconds (healthy) ...
{"status":"UP","app":"ShopRung","version":"1.0.0"}
shoprung-1  | GET /api/health -> 200 (0 ms)
...

Check it works

From a clean state (down -v), run both suites: api-tests gives 23 passed and exit code 0, e2e gives 7 passed. Then run api-tests with SHOPRUNG_BUGS=coupon-boundary after a down -v: 1 failed, 22 passed, exit code 1, and the failure is test_save10_applies_at_exactly_50_dollars with assert 400 == 200.

Finally docker compose -f compose.test.yaml ps -a after down -v shows nothing: no containers, no leftovers.

Test
docker compose -f compose.test.yaml down -v
docker compose -f compose.test.yaml run --rm api-tests
docker compose -f compose.test.yaml run --rm e2e
You should see
============================== 23 passed in 0.76s ==============================
...
  7 passed (1.8s)

Troubleshooting

Cannot connect to the Docker daemon.

Docker Desktop is not running (or, on Linux, the docker service is stopped). Start it and try again.

Playwright: "Executable doesn't exist at /ms-playwright/...".

The image tag and the @playwright/test version differ. Make the image v1.63.0-noble match package.json.

Tests reach localhost and fail to connect.

Inside Compose, use the service name: BASE_URL: http://shoprung:8080.

npm errors about esbuild or platform binaries after running the e2e container.

Keep the anonymous /e2e/node_modules volume so the container never writes into your machine's node_modules.

Old data or a bug is still on.

docker compose -f compose.test.yaml down -v and run again: a new ShopRung container starts from seed data.

What changes in production

  • Teams keep a compose file like this next to the code so every developer, tester and CI agent gets the same app, database and test images.
  • Images are pinned to exact versions (and often to digests); latest is never used for test infrastructure.
  • Real systems add their database, queues and stubs (WireMock, a fake payment provider) as more services, each with a health check.
  • For integration tests inside test code, Testcontainers starts the same containers from JUnit or pytest instead of Compose.

Interview angle

“How do you run tests in Docker?”

With a Compose file: the application built from its Dockerfile with a health check, and test services using pinned official images, the Python image for pytest and the Playwright image that matches our Playwright version for UI tests. Test services depend on the app with condition service_healthy and reach it by service name, never localhost. docker compose run --rm returns the test exit code, which CI uses, and down -v gives a clean start. The same file runs on laptops and CI, so environments match, and logs are collected before teardown.

Clean up

Practice

These run in your browser and check your answer.

Start order from depends_on

Compose starts services after the ones they depend on. Write start_order(deps) where deps maps each service to the list it depends on, and return a list of every service in a valid start order (dependencies first). If several are ready at once, take them in alphabetical order.

Exercise
def start_order(deps):
    return sorted(deps)
Hint

Repeat: pick the services whose dependencies are all started, sort them, take the first one.

The full project

Every file from this lab, as it is after the last step.

Download Docker Compose project (.zip)