Run Playwright Python Tests in Docker (Official Image, Dockerfile, Compose)

“It works on my machine” usually means different browser builds, system libraries, fonts or Python versions. Docker removes those differences: the tests run inside an image that is identical on every laptop and CI agent. Microsoft publishes an official Playwright Python image with Python, all browsers and their dependencies. In this lesson you will pick the right image tag, run your suite in a throwaway container, build your own test image with a Dockerfile, pass secrets and collect reports through volumes, orchestrate tests next to an application with docker compose, and run browsers in a container that your tests connect to remotely.

Advertisement

📖 What You’ll Learn: why Docker for browser tests, the official mcr.microsoft.com/playwright/python image and its tags (noble, jammy, resolute), matching the image to your Playwright version, docker run with a bind mount, –ipc=host and –init, a Dockerfile for a test image, .dockerignore, running as the non-root pwuser, passing secrets with -e and –env-file, getting reports out with volumes, docker compose with a service under test, playwright run-server and connecting with connect_options, and a comparison of the approaches.


🐳 Why Run Tests in Docker?

Without Docker With Docker
Each machine has its own OS, fonts and libraries Everyone uses the same image
playwright install --with-deps needs admin rights on Linux Browsers and dependencies are already in the image
Screenshot baselines differ between laptops and CI Rendering is identical, so visual tests are stable
CI agents need Python and browsers pre-installed Any agent that can run Docker can run the tests

🏷️ The Official Image and Its Tags

Microsoft publishes mcr.microsoft.com/playwright/python. Tags combine the Playwright version and the Ubuntu release:

Tag Base
v1.65.2-noble Ubuntu 24.04 LTS (recommended default)
v1.65.2-jammy Ubuntu 22.04 LTS
v1.65.2-resolute Ubuntu 26.04

Each also exists with -amd64 / -arm64 suffixes. Always use the tag that matches the playwright version in your requirements.txt. A Playwright package looks for the browser builds of its own release; a mismatch fails with “Executable doesn’t exist”.

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0

📄 check_versions.py

"""Fail fast when the Docker image tag and the pinned playwright version differ."""
import re
import sys

IMAGE = "mcr.microsoft.com/playwright/python:v1.65.2-noble"

pinned = re.search(r"^playwright==([\d.]+)$", open("requirements.txt").read(), re.M).group(1)
tagged = re.search(r":v([\d.]+)-", IMAGE).group(1)
print(f"requirements.txt: {pinned} | image tag: {tagged}")
sys.exit(0 if pinned == tagged else "versions differ: update the image tag")

⌨️ Terminal

python check_versions.py

🖥️ Output

requirements.txt: 1.65.2 | image tag: 1.65.2

A check like this in CI catches the most common Docker problem before any test runs.


▶️ Run the Suite in a Throwaway Container

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_shop.py

from playwright.sync_api import Page, expect


def test_home(page: Page):
    page.goto("/dummy-ecommerce-website/")
    expect(page.get_by_test_id("product-card").first).to_be_visible()


def test_search(page: Page):
    page.goto("/dummy-ecommerce-website/#/search/course")
    expect(page.get_by_test_id("product-card").first).to_be_visible()

Run the tests inside the image, with your project folder mounted:

⌨️ Terminal

docker run --rm --ipc=host --init -v "${PWD}:/work" -w /work mcr.microsoft.com/playwright/python:v1.65.2-noble bash -c "pip install -r requirements.txt && pytest"
Part Meaning
--rm Delete the container afterwards
--ipc=host Recommended for Chromium: the default shared memory in Docker is too small and can crash it
--init A tiny init process that reaps zombie browser processes
-v "${PWD}:/work" -w /work Mount the project into the container and work there; results appear on your disk

${PWD} works in PowerShell and bash; in the old Windows cmd use %cd%.


📦 Build Your Own Test Image

For CI it is faster and more repeatable to bake the dependencies into an image:

📄 Dockerfile

FROM mcr.microsoft.com/playwright/python:v1.65.2-noble

WORKDIR /tests

# Dependencies first: this layer is cached until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Then the test code
COPY . .

# Run as the image's non-root user
RUN chown -R pwuser:pwuser /tests
USER pwuser

ENTRYPOINT ["pytest"]
CMD ["-q"]

📄 .dockerignore

.venv/
.git/
.env*
.auth/
test-results/
reports/
__pycache__/
.pytest_cache/

Build and run:

⌨️ Terminal

docker build -t shop-tests:1.0 .
docker run --rm --ipc=host --init shop-tests:1.0
docker run --rm --ipc=host --init shop-tests:1.0 -m smoke --browser firefox
  • Copying requirements.txt before the rest of the code means changing a test does not reinstall packages: Docker reuses the cached layer.
  • ENTRYPOINT ["pytest"] plus CMD ["-q"] makes the container behave like the pytest command: arguments after the image name replace CMD.
  • .dockerignore keeps secrets (.env, .auth/), old results and the local virtual environment out of the image.
  • pwuser is a non-root user that exists in the official image. Running browsers as root disables Chromium’s sandbox, so avoid it.

A quick self-check of these rules:

📄 check_dockerfile.py

from pathlib import Path

dockerfile = Path("Dockerfile").read_text()
ignored = Path(".dockerignore").read_text().split()
checks = {
    "image tag pinned (no :latest)": ":latest" not in dockerfile and ":v" in dockerfile,
    "requirements copied before code": dockerfile.index("COPY requirements.txt") < dockerfile.index("COPY . ."),
    "runs as non-root user": "USER pwuser" in dockerfile,
    "secrets ignored": ".env*" in ignored and ".auth/" in ignored,
}
for name, ok in checks.items():
    print(("PASS " if ok else "FAIL ") + name)

⌨️ Terminal

python check_dockerfile.py

🖥️ Output

PASS image tag pinned (no :latest)
PASS requirements copied before code
PASS runs as non-root user
PASS secrets ignored

Advertisement

🔐 Secrets and Results

Secrets go in at run time, never into the image:

⌨️ Terminal

docker run --rm --ipc=host -e SHOP_USER -e SHOP_PASSWORD shop-tests:1.0
docker run --rm --ipc=host --env-file .env.qa shop-tests:1.0

-e NAME without a value copies the variable from your shell. --env-file reads a file (keep it out of Git).

Results come out through a volume:

⌨️ Terminal

docker run --rm --ipc=host -v "${PWD}/results:/tests/test-results" shop-tests:1.0 --tracing retain-on-failure --screenshot only-on-failure

Traces and screenshots of failed tests now appear in ./results on your machine, ready for playwright show-trace (Lesson 62).


🧩 docker compose: Tests Next to the Application

When the application under test also runs in a container (common for pull-request environments), compose starts both and connects them on one network:

📄 compose.yaml

services:
  shop:
    image: nginx:1.27-alpine                       # stands in for your application image
    volumes:
      - ./site:/usr/share/nginx/html:ro
    healthcheck:
      test: ["CMD", "wget", "-q", "-O", "-", "http://localhost/"]
      interval: 2s
      retries: 15

  tests:
    build: .
    ipc: host
    init: true
    depends_on:
      shop:
        condition: service_healthy                 # wait until the app answers
    environment:
      PYTEST_BASE_URL: http://shop                 # the service name is the host name
    command: ["-q", "-m", "smoke"]
    volumes:
      - ./results:/tests/test-results

⌨️ Terminal

docker compose up --build --exit-code-from tests
  • Service names are DNS names on the compose network, so the tests reach the app at http://shop.
  • PYTEST_BASE_URL sets --base-url (Lesson 47), so no test changes.
  • --exit-code-from tests stops everything when the tests finish and returns their exit code, which makes CI pass or fail correctly.

📄 check_compose.py

import yaml

compose = yaml.safe_load(open("compose.yaml", encoding="utf-8"))
tests = compose["services"]["tests"]
print("services:", list(compose["services"]))
print("tests wait for:", tests["depends_on"])
print("base url:", tests["environment"]["PYTEST_BASE_URL"])

⌨️ Terminal

python check_compose.py

🖥️ Output

services: ['shop', 'tests']
tests wait for: {'shop': {'condition': 'service_healthy'}}
base url: http://shop

🌐 Browsers in a Container, Tests Anywhere

Sometimes the tests should run on your machine (fast edit-run loop, debugger) while the browsers run in Linux, for example to get the same screenshots as CI. Playwright includes a browser server for this:

⌨️ Terminal

docker run --rm --init --ipc=host -p 3000:3000 --user pwuser mcr.microsoft.com/playwright/python:v1.65.2-noble playwright run-server --port 3000 --host 0.0.0.0

pytest-playwright connects to it when the connect_options fixture returns an endpoint. Note the key name: Playwright 1.65 calls it endpoint (older versions used ws_endpoint, which now raises TypeError: ... unexpected keyword argument 'ws_endpoint'):

📄 tests/conftest.py

import os

import pytest


@pytest.fixture(scope="session")
def connect_options():
    endpoint = os.getenv("PW_WS_ENDPOINT")                  # e.g. ws://127.0.0.1:3000/
    return {"endpoint": endpoint} if endpoint else None      # None = launch a local browser as usual

To try it without Docker, this script starts the same server locally (exactly what the container runs), points the tests at it, then stops it:

📄 remote_demo.py

import os
import subprocess
import sys
import time

server = subprocess.Popen(["playwright", "run-server", "--port", "3123", "--host", "127.0.0.1"],
                          stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
try:
    print("server:", server.stdout.readline().strip())          # "Listening on ws://127.0.0.1:3123/"
    env = {**os.environ, "PW_WS_ENDPOINT": "ws://127.0.0.1:3123/"}
    result = subprocess.run([sys.executable, "-m", "pytest", "-q", "tests"], env=env, capture_output=True, text=True)
    print(result.stdout.strip().splitlines()[-1])
finally:
    if os.name == "nt":      # on Windows, also stop the Node.js process the playwright launcher started
        subprocess.run(["taskkill", "/T", "/F", "/PID", str(server.pid)], capture_output=True)
    else:
        server.terminate()
    server.wait(timeout=10)

⌨️ Terminal

python remote_demo.py

🖥️ Output

server: Listening on ws://127.0.0.1:3123/
2 passed in 3.97s

The tests passed using browsers launched by the server process, not by pytest. With the container, the only difference is the endpoint (ws://127.0.0.1:3000/ mapped from Docker). Keep the client and server Playwright versions equal; the protocol is not compatible across versions.


⚖️ Which Approach When?

Approach Best for
docker run with a bind mount Trying the suite in Linux quickly; no image to maintain
Your own test image (Dockerfile) CI agents, reproducible runs, sharing the suite
docker compose Testing an application that also runs in containers
Remote browser server Local test code with CI-identical browsers; central browser hosts
CI container option (Lesson 66) GitHub Actions jobs that run directly in the image

Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write the docker run command that runs only the smoke tests in Firefox from your built shop-tests:1.0 image and saves failure traces to ./results.

Show answer
docker run --rm --ipc=host --init -v "${PWD}/results:/tests/test-results" shop-tests:1.0 -m smoke --browser firefox --tracing retain-on-failure

Everything after the image name replaces the Dockerfile’s CMD, and the ENTRYPOINT adds pytest in front.

Exercise 2: Your teammate’s Dockerfile starts with FROM mcr.microsoft.com/playwright/python:latest. Why is that risky, and what should it be?

Show answer

latest changes whenever Microsoft publishes a new release, so the browsers in the image can stop matching the pinned playwright package (and tests can change behaviour without any code change). Pin the exact tag that matches requirements.txt, such as v1.65.2-noble, and update both together.

Exercise 3: Reorder this Dockerfile so that changing a test file does not reinstall all packages:

COPY . .
RUN pip install -r requirements.txt
Show answer
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

Docker caches each layer; the install layer is reused until requirements.txt changes.

Exercise 4: In compose, the tests start before the app is ready and fail with connection errors. What do you add?

Show answer

A healthcheck on the app service and depends_on: { shop: { condition: service_healthy } } on the tests service, so compose starts the tests only after the app answers.


🧠 MCQ Quiz: Playwright Python in Docker

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which image does Microsoft publish for Playwright Python?
  2. Why must the image tag match the playwright version you install?
  3. What does --ipc=host help with?
  4. Why copy requirements.txt before the rest of the code in a Dockerfile?
  5. What belongs in .dockerignore for a test project?
  6. How should secrets reach the container?
  7. How do test results get out of a container?
  8. In compose, how do the tests reach the app service named shop?
  9. Which fixture makes pytest-playwright connect to a remote browser server?
  10. Which command starts Playwright’s browser server?

Want a longer, timed test? Take the Module 12 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Can I run headed browsers in Docker?

Not usefully without a display. Use traces, videos and screenshots instead, or run tests locally against a remote browser only when you need to watch.

🤔 Is the image large?

Yes, around 1.5 to 2 GB because it contains three browsers. CI runners cache it after the first pull, and you can build a smaller custom image with only Chromium (playwright install --with-deps chromium on a slim Python base) if size matters.

🤔 Does Docker work on Windows and macOS?

Yes, through Docker Desktop (Linux containers). The tests then run in Linux, which is exactly what makes results match Linux CI agents.

🤔 Should the test image contain the tests or mount them?

Mount them for local runs (instant edits); bake them into the image for CI and for sharing a fixed version of the suite.

🤔 Can I use the remote browser server with xdist?

Yes. Each worker opens its own connection; raise the server’s --max-clients if needed, and give the container enough CPU and memory for several browsers.


Advertisement

🏁 Summary

  • Use mcr.microsoft.com/playwright/python:v<version>-noble with the same version as your playwright package.
  • Run throwaway containers with --rm --ipc=host --init and a bind mount, or build a test image with a cache-friendly Dockerfile, .dockerignore and the non-root pwuser.
  • Pass secrets with -e/--env-file and collect results through volumes.
  • Use docker compose with healthchecks and --exit-code-from tests to test containerised apps.
  • Run browsers in a container with playwright run-server and connect from pytest through the connect_options fixture.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page