Running Playwright in Docker: A Complete Production Guide

Dockerfiles, Compose, shared memory, resource limits, crash handling and scaling for Playwright in Docker — and when to skip the containers.

Spectrae team · · 8 min read

Playwright in Docker looks simple on paper. Pull an image, install a browser, run your script. Done.

Except it's never that simple.

The moment you try to run Chromium inside a container on a real server, you hit a wall of system dependency errors, sandbox failures, shared memory crashes, and OOM kills that no tutorial warned you about. Getting a browser to launch is one thing. Keeping it stable under load, with proper resource limits and restart behavior, is a different problem entirely.

This guide covers the real setup — Dockerfile, Compose, resource constraints, crash handling, scaling patterns, and when it makes more sense to just skip the containers altogether.

Why Playwright in Docker is trickier than you'd expect

Browsers are not small, stateless binaries. Chromium alone pulls in dozens of shared libraries — fonts, audio codecs, graphics drivers, and sandbox kernel modules — that most base images don't include. On a fresh Ubuntu or Debian image, playwright install chromium (without --with-deps) will succeed, but launching the browser will throw errors about missing libgbm, libnss3, libatk, and a half-dozen other system packages.

On top of that, Chromium uses a multi-process sandbox architecture. Child processes run with restricted Linux namespaces and seccomp filters. Inside Docker's default security profile, that sandbox needs extra privileges or a custom seccomp profile to work, which is why most container setups run Chromium with its sandbox disabled and rely on the container for isolation.

Then there's shared memory. By default, Docker gives containers 64MB of /dev/shm. Chromium uses shared memory heavily. That 64MB limit can make the browser crash on heavier pages, often without an obvious error message.

None of this is unsolvable. But you need to know it going in.

The Dockerfile challenges

The two most reliable starting points are the official Microsoft Playwright image or a Node.js base image with --with-deps during browser install.

The official image is the simpler path:

FROM mcr.microsoft.com/playwright:v1.58.2-noble

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

CMD ["node", "scraper.js"]

That image ships with the system dependencies and browsers for Chromium, Firefox, and WebKit pre-installed. The tradeoff is image size — it's well over a gigabyte.

If you need something leaner, start from Node and install deps yourself:

FROM node:22-bookworm-slim

# Install system dependencies for Chromium
RUN apt-get update && apt-get install -y \
    libgbm1 \
    libnss3 \
    libatk-bridge2.0-0 \
    libdrm2 \
    libxkbcommon0 \
    libxcomposite1 \
    libxdamage1 \
    libxrandr2 \
    libpango-1.0-0 \
    libcairo2 \
    libasound2 \
    fonts-liberation \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Install browsers to a shared path so the non-root user below can find them
# (by default Playwright uses the installing user's ~/.cache).
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright

COPY package*.json ./
RUN npm ci
# --with-deps would also install the system packages above for you
RUN npx playwright install chromium

# Run as non-root for better security
RUN groupadd -r pwuser && useradd -r -g pwuser -G audio,video pwuser \
    && mkdir -p /home/pwuser \
    && chown -R pwuser:pwuser /home/pwuser /app

USER pwuser

COPY --chown=pwuser:pwuser . .

CMD ["node", "scraper.js"]

Key things to get right:

  • Pin the Playwright version in your package.json and match it to the image tag. A mismatch means Playwright can't find its browser executables.
  • Alpine Linux is not supported. Chromium and Firefox builds target glibc. Alpine uses musl. Use Debian or Ubuntu variants.
  • Run as a non-root user. Playwright launches Chromium with its sandbox disabled by default (chromiumSandbox: false), so the container is your isolation boundary — don't hand a compromised renderer root inside it.

Docker Compose for browser + automation services

A real production setup usually separates the browser server from your application logic. Here's a Compose file that runs a Playwright browser server as its own service, with your scraper connecting to it over the network:

services:
  browser:
    image: mcr.microsoft.com/playwright:v1.58.2-noble
    # Keep the run-server version identical to the image tag and your client
    command: >
      npx -y [email protected] run-server
      --port 3000
      --host 0.0.0.0
    ports:
      - "3000:3000"
    shm_size: "2gb"
    init: true
    restart: on-failure
    deploy:
      resources:
        limits:
          memory: 3G
          cpus: "2.0"

  scraper:
    build: .
    depends_on:
      - browser
    environment:
      - BROWSER_WS_ENDPOINT=ws://browser:3000
    restart: on-failure

Your scraper then connects over WebSocket instead of launching a browser locally:

const { chromium } = require('playwright');

const browser = await chromium.connect(process.env.BROWSER_WS_ENDPOINT);
const page = await browser.newPage();

await page.goto('https://example.com');
// ... your scraping logic

await browser.close();

This separation is useful. The browser service can crash and restart without taking your application code with it. You can also scale the browser tier independently.

Resource limits for browser containers

Get these wrong and containers will die in production without obvious errors.

Resource Minimum Recommended (prod)
Memory per container 1 GB 2–3 GB
Shared memory (/dev/shm) 256 MB 1–2 GB
CPU 0.5 cores 1–2 cores
Concurrent pages per container 1–2 3–5

A few settings that matter more than most guides mention:

shm_size — Set this in your Compose file. The default 64MB is too small for Chromium on many real pages. 1–2GB is a common production value.

--init flag — Pass --init to Docker or set init: true in Compose. Browsers spawn child processes. Without a proper init process, zombie processes accumulate and eventually cause strange failures.

--ipc=host — Playwright's Docker docs recommend this for Chromium to avoid running out of shared memory, though it reduces isolation. Weigh that tradeoff for your threat model.

--disable-dev-shm-usage — If you can't set shm_size, pass this flag to Chromium at launch. It tells Chromium to use /tmp instead of /dev/shm, avoiding crashes at some cost to performance.

Handling container crashes and restarts

Browsers crash. That's just reality. Memory pressure, malformed pages, rendering bugs in specific sites — crashes will happen under any sustained load.

Set restart: on-failure rather than restart: always in production. The always policy will restart a container even after a clean exit, which creates problems for one-shot jobs and can mask real failures.

Check if a container was OOM-killed after unexpected restarts:

docker inspect <container_id> --format '{{.State.OOMKilled}}'

If that returns true, you need more memory or fewer concurrent pages. No amount of retry logic fixes an undersized container.

For health checks, note that playwright run-server doesn't expose an HTTP health endpoint. A simple option is to check that the port accepts connections, using Node since the image already has it:

healthcheck:
  test: ["CMD", "node", "-e", "require('net').connect(3000,'127.0.0.1').on('connect',()=>process.exit(0)).on('error',()=>process.exit(1))"]
  interval: 30s
  timeout: 10s
  retries: 3
  start_period: 15s

A port check proves the server is listening, not that a browser launches. For that, run a small scheduled job that connects, opens about:blank, and disconnects.

Scaling with multiple containers

Running multiple browser containers is straightforward in Compose:

docker compose up --scale browser=4

Remove the fixed ports: - "3000:3000" mapping first: four replicas can't all bind the same host port. Your scraper reaches them over the Compose network instead.

But now you need something in front of them. Your scraper needs to know which browser endpoint to connect to. The most common patterns are:

Static assignment — Each worker knows its own browser endpoint via environment variable. Simple, but no failover if one container dies.

Load balancer — Put an nginx or HAProxy in front of the browser services and route WebSocket connections. More setup, but gives you failover and a single connection endpoint.

Pool pattern — Your application maintains a list of available browser endpoints and claims them before use. This is what production scraping systems actually do at scale.

const endpoints = [
  'ws://browser-1:3000',
  'ws://browser-2:3000',
  'ws://browser-3:3000',
  'ws://browser-4:3000',
];

async function getBrowser() {
  const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];
  return chromium.connect(endpoint);
}

At meaningful scale — say, 20+ concurrent browsers — you're now maintaining a container orchestration layer, a connection pool, health monitoring, and restart logic. That's a real engineering surface area.

Connecting to a remote browser API instead

At some point, the infrastructure you're managing to run browsers starts costing more than the browsers themselves.

Spectrae gives you remote, isolated browsers accessible over WebSocket. You connect Playwright to the endpoint and run your scraping logic exactly as you normally would — no Dockerfiles, no memory limits, no restart policies.

const { chromium } = require('playwright');

const browser = await chromium.connect(
  `wss://browser.spectrae.dev/standard/playwright?key=${process.env.SPECTRAE_API_KEY}`
);

const page = await browser.newPage();
await page.goto('https://example.com');

const data = await page.evaluate(() => {
  return document.title;
});

console.log(data);
await browser.close();

That's the entire setup. No shm_size, no --init, no --disable-dev-shm-usage, no health checks, no OOM debugging. The browser infrastructure is handled. You keep the scraping logic.

Pricing is per second: $0.003/min for the standard browser, so a 5-minute session costs $0.015. For many workloads, that's well under what it costs in engineering time to manage the equivalent Docker setup.

A Camoufox-powered stealth browser ($0.05/min) is also available on the same API when you need a Firefox fingerprint for protected sites — see Playwright stealth.

When to manage your own containers vs use a BaaS

Both approaches are valid. The right choice depends on your situation.

Run your own containers when:

  • You're processing millions of pages per day and unit economics require it
  • You have compliance requirements that prohibit third-party browser infrastructure
  • You need custom browser patches or specific browser versions not available elsewhere
  • You already have a DevOps team maintaining container infrastructure for other services

Use a remote browser API when:

  • You're moving fast and want to ship scraping logic, not infrastructure
  • Your volume is variable and you don't want to pay for idle containers
  • You're a small team and DevOps bandwidth is limited
  • You'd rather add concurrent sessions from a dashboard than provision servers

The middle ground — running your scraping logic yourself while offloading the browser layer to a managed service — gives you most of the control without the ops overhead.

The bottom line

Running Playwright in Docker is doable. The Dockerfile challenges are solvable, the resource limits are learnable, and the crash-handling patterns are well-established.

But it's not free. Every hour you spend tuning shm_size and debugging OOM kills is an hour not spent on the scraping logic that actually creates value.

If you want the browser infrastructure handled so you can focus on what you're actually building, try Spectrae. Connect your existing Playwright code with a one-line change and skip the browser containers entirely.

Get an API key with $1 of free credit, or read the docs.