π³ Hermetic Environments: Eliminating the "Works on My Machine" Dilemma
Operating system variances create subtle, frustrating defects in web automation: different OS kernels render fonts with varying antialiasing weights (breaking visual regression baselines), missing system libraries (such as libgbm, libasound2, or font packages) cause browser process crashes on headless servers, and unmanaged shared memory limits lead to Chromium tab crashes. Docker containerization provides a 100% reproducible execution runtime. By utilizing Microsoft's official mcr.microsoft.com/playwright/python container images, browser binaries (Chromium, Firefox, WebKit) and OS-level system libraries come pre-packaged and pre-configured. Engineers can execute entire test suites in isolated sandboxes locally, across Kubernetes clusters, or in CI/CD without installing browser binaries on the host system.
/dev/shm partition, which causes browser crashes unless properly configured with --ipc=host or --shm-size=2gb.
PLAYWRIGHT CONTAINER RUNTIME TOPOGRAPHY:
HOST MACHINE (Developer Laptop / GitHub Actions Runner / Jenkins Node)
βββ Host Filesystem: /home/user/project (Mounted via -v)
βββ Host Network / Ports: 8080, 9323 (Mapped via -p)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DOCKER CONTAINER: mcr.microsoft.com/playwright/python:v1.43.0-jammy β
β β
β βββ SHARED MEMORY ALLOCATION: β
β β β Default Docker /dev/shm (64MB) βββΊ Chromium Tab Crash (OOM) β
β β β
Configured: --ipc=host OR --shm-size=2gb βββΊ High Performance Frame β
β β β
β βββ PRE-INSTALLED SYSTEM RUNTIMES: β
β β * Ubuntu 22.04 LTS (Jammy Jellyfish base) β
β β * Python 3.11 Runtime + pip β
β β * Fonts: DejaVu Sans, Noto Sans, FreeSans (Deterministic Visuals) β
β β * Pre-baked Browsers: ~/.cache/ms-playwright (Chromium, FF, WebKit) β
β β β
β βββ CONTAINERIZED EXECUTION PIPELINE: β
β pytest -n auto --alluredir=/workspace/allure-results β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β²
βββ Real-time write back to host: /workspace/allure-results βββΊ Host Results
/workspace and forward test execution commands.
# Run tests inside ephemeral Docker container with volume mounting
docker run --rm -it \
--ipc=host \
-v $(pwd):/workspace \
-w /workspace \
mcr.microsoft.com/playwright/python:v1.43.0-jammy \
/bin/bash -c "pip install -r requirements.txt && pytest -n auto --tracing retain-on-failure"
# PowerShell syntax on Windows 10/11
docker run --rm -it `
--ipc=host `
-v ${PWD}:/workspace `
-w /workspace `
mcr.microsoft.com/playwright/python:v1.43.0-jammy `
/bin/bash -c "pip install -r requirements.txt && pytest -n auto --tracing retain-on-failure"
Dockerfile that bakes Python requirements directly into the image layer, sets non-root security boundaries, and minimizes container build times.
# Base image pinned to exact Playwright version matching requirements.txt
FROM mcr.microsoft.com/playwright/python:v1.43.0-jammy
# Set non-interactive environment variables and Python buffer flags
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1
# Create non-root application directory
WORKDIR /app
# Layer Caching: Copy requirements first to cache dependency installations
COPY requirements.txt .
# Upgrade pip and install all Python framework dependencies
RUN pip install --upgrade pip && \
pip install -r requirements.txt
# Copy complete automation framework code
COPY . .
# Set non-root user permissions for security hardening
RUN chown -R pwuser:pwuser /app
USER pwuser
# Default container entrypoint executing parallel regression suite
CMD ["pytest", "-n", "auto", "--dist", "loadscope", "--alluredir=allure-results"]
version: "3.8"
services:
# 1. Mock Backend REST API Server
mock-api:
image: mockoon/cli:latest
ports:
- "3000:3000"
command: ["--data", "/data/mock-schema.json", "--port", "3000"]
volumes:
- ./tests/mocks:/data:ro
# 2. Local Web Application Frontend
web-app:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./dist:/usr/share/nginx/html:ro
depends_on:
- mock-api
# 3. Playwright Test Runner Service
playwright-runner:
build:
context: .
dockerfile: docker/Dockerfile
ipc: host # Shared memory allocation for Chromium
environment:
- BASE_URL=http://web-app:80
- API_BASE_URL=http://mock-api:3000
- TEST_ENV=docker_grid
volumes:
# Map host results folder so test outputs persist on host
- ./allure-results:/app/allure-results
- ./test-results:/app/test-results
depends_on:
- web-app
command: ["pytest", "-n", "2", "--tracing", "retain-on-failure"]
# Execute entire grid, run tests, and tear down containers automatically
docker compose up --build --abort-on-container-exit --exit-code-from playwright-runner
docker compose down
from playwright.sync_api import Page, expect
def test_enterprise_billing_header_visual(page: Page):
"""Visual regression test guaranteed deterministic when executed in Docker."""
page.set_viewport_size({"width": 1280, "height": 720})
page.set_content("""
Nikita-Infotech Consolidated Ledger
Active Services: 14
Status: Verified
""")
card_locator = page.locator("div > div")
# When executed inside Docker, font antialiasing and subpixel geometry are identical
expect(card_locator).to_have_screenshot("docker_billing_header.png")
print("Visual snapshot verified under standardized Linux rendering engine!")
# Update golden baseline images using the exact Docker environment:
docker run --rm -it \
--ipc=host \
-v $(pwd):/workspace \
-w /workspace \
mcr.microsoft.com/playwright/python:v1.43.0-jammy \
pytest tests/test_docker_visual.py --update-snapshots
FROM mcr.microsoft.com/playwright/python:v1.43.0-jammy
# Install Xvfb, fluxbox window manager, and x11vnc server
RUN apt-get update && apt-get install -y --no-install-recommends \
xvfb \
x11vnc \
fluxbox \
novnc \
websockify && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
# Expose VNC port (5900) and noVNC web port (6080)
EXPOSE 5900 6080
# Launch script that starts Xvfb, VNC, noVNC web interface, and runs pytest
COPY docker/entrypoint_vnc.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
#!/bin/bash
# Start virtual display buffer
Xvfb :99 -screen 0 1920x1080x24 &
export DISPLAY=:99
# Start window manager and VNC server
fluxbox &
x11vnc -display :99 -nopw -listen 0.0.0.0 -xkb &
websockify --web=/usr/share/novnc/ 6080 localhost:5900 &
echo "[noVNC Started] Connect browser to: http://localhost:6080/vnc.html"
# Run tests in headed mode so they render into the virtual display!
pytest --headed --slowmo 300 "$@"
localhost:8080), configure host.docker.internal network routing.
import os
def get_target_base_url() -> str:
"""Detects whether tests are running inside Docker and resolves host address."""
# Check if executing inside a Docker container
is_docker = os.path.exists("/.dockerenv")
if is_docker:
# Route from container to local host machine's port 8080
host_target = "host.docker.internal"
print(f"[Network Route] Docker container detected. Routing to: http://{host_target}:8080")
return f"http://{host_target}:8080"
else:
# Standard local execution on host
return "http://localhost:8080"
# CLI execution command on Linux host (requires --add-host flag):
# docker run --rm -it --ipc=host --add-host=host.docker.internal:host-gateway ...
docker run --rm -it \
--ipc=host \
--add-host=host.docker.internal:host-gateway \
-v $(pwd):/workspace \
-w /workspace \
mcr.microsoft.com/playwright/python:v1.43.0-jammy \
pytest tests/test_local_server.py
PermissionError: [Errno 13] Permission denied) when tests write traces, screenshots, and Allure files from inside Docker back to your host filesystem.
# Pass current host user's UID and GID to container
# This ensures generated failure traces and allure-results are owned by YOU on the host!
docker run --rm -it \
--ipc=host \
--user $(id -u):$(id -g) \
-v $(pwd):/workspace \
-w /workspace \
mcr.microsoft.com/playwright/python:v1.43.0-jammy \
pytest --alluredir=/workspace/allure-results --output=/workspace/test-results
# content of conftest.py
import os
import pytest
from pathlib import Path
@pytest.fixture(scope="session", autouse=True)
def ensure_output_directories_exist():
"""Guarantees directories exist with write permissions before test execution."""
output_paths = [
Path("allure-results"),
Path("test-results"),
Path("test-results/traces")
]
for p in output_paths:
p.mkdir(parents=True, exist_ok=True)
# Ensure write permissions for active process user
os.chmod(p, 0o777)
print("\n[Docker Setup] Output directories initialized with write permissions.")
name: Containerized Playwright CI
on:
push:
branches: [main]
jobs:
run-container-suite:
runs-on: ubuntu-latest
# Execute job directly inside official pre-baked container
container:
image: mcr.microsoft.com/playwright/python:v1.43.0-jammy
options: --ipc=host --user 1001
steps:
- name: Checkout Code
uses: actions/checkout@v4
# Python and Playwright browsers are ALREADY installed!
- name: Install Project Requirements
run: |
pip install --no-cache-dir -r requirements.txt
- name: Execute Parallel Test Suite
run: |
pytest -n auto --dist loadscope \
--alluredir=allure-results \
--tracing retain-on-failure
- name: Upload Failure Artifacts
if: failure()
uses: actions/upload-artifact@v4
with:
name: docker-failure-traces
path: test-results/**/trace.zip
retention-days: 7
PLAYWRIGHT DOCKER CONTAINER REFERENCE MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Configuration / Flag β Example Usage β Purpose / Architectural Impact β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Official Image Tag β mcr.microsoft.com/playwright/β Canonical Microsoft Ubuntu Jammy image with browsers. β
β β python:v1.43.0-jammy β β
β Shared Memory Flag β --ipc=host β Shares host memory; prevents Chromium OOM tab crashes. β
β Shared Memory Alternative β --shm-size=2gb β Explicitly sets 2GB shared memory for Docker daemon. β
β Host Volume Mount β -v $(pwd):/workspace β Maps local framework into container working directory. β
β Working Directory β -w /workspace β Sets active execution folder inside container. β
β User ID Mapping β --user $(id -u):$(id -g) β Guarantees output files are owned by host user, not rootβ
β Host Network Resolution β --add-host=host.docker.inte..β Allows container to access localhost services on host. β
β Headless Environment Variableβ ENV PYTHONUNBUFFERED=1 β Flushes stdout immediately for real-time terminal logs. β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β BEST PRACTICE GUIDELINES: β
β 1. Always pin the Docker image tag version (e.g. v1.43.0-jammy) to match the playwright version in requirements.txt. β
β 2. Use Docker for visual regression baselines to avoid subtle macOS vs. Linux font antialiasing discrepancies. β
β 3. In docker-compose, set 'ipc: host' on the test runner service to support high-concurrency multi-worker testing. β
β 4. Never run containers as root in shared CI environments; map permissions via non-root user (pwuser). β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ