Playwright with Docker: Complete Setup

Playwright with Docker: Complete Setup

Here’s a complete setup guide for running Playwright with Docker, perfect for CI/CD or isolated test environments.


🧰 Tools Used

Playwright (end-to-end testing framework)


Docker (containerization platform)


Node.js environment inside Docker


πŸ“ Project Structure

lua

Copy

Edit

your-project/

├── tests/

│   └── example.spec.ts

├── package.json

├── playwright.config.ts

└── Dockerfile

πŸ“¦ 1. package.json

Basic Playwright project:


json

Copy

Edit

{

  "name": "playwright-docker-example",

  "version": "1.0.0",

  "scripts": {

    "test": "playwright test"

  },

  "devDependencies": {

    "@playwright/test": "^1.45.0"

  }

}

πŸ§ͺ 2. Sample Test (tests/example.spec.ts)

ts

Copy

Edit

import { test, expect } from '@playwright/test';


test('homepage has title', async ({ page }) => {

  await page.goto('https://playwright.dev');

  await expect(page).toHaveTitle(/Playwright/);

});

⚙️ 3. Playwright Config (playwright.config.ts)

ts

Copy

Edit

import { defineConfig } from '@playwright/test';


export default defineConfig({

  testDir: './tests',

  timeout: 30000,

  use: {

    headless: true,

    viewport: { width: 1280, height: 720 },

    screenshot: 'only-on-failure',

    video: 'retain-on-failure',

  },

});

🐳 4. Dockerfile

Dockerfile

Copy

Edit

# Use official Node base image

FROM mcr.microsoft.com/playwright:v1.45.0-jammy


# Set working directory

WORKDIR /app


# Copy files

COPY package.json package-lock.json ./

RUN npm ci


COPY . .


# Run tests by default

CMD ["npx", "playwright", "test"]

✅ This image already includes browsers and dependencies (headless Chromium, Firefox, WebKit).


πŸ—️ 5. Build & Run Docker Container

Build the image:

bash

Copy

Edit

docker build -t playwright-docker .

Run the container:

bash

Copy

Edit

docker run --rm playwright-docker

If using volume mounts (to sync test files live):


bash

Copy

Edit

docker run --rm -v "$PWD:/app" playwright-docker

πŸ§ͺ Optional: CI/CD Integration

Add this to a GitHub Actions workflow:


yaml

Copy

Edit

- name: Run Playwright tests in Docker

  run: |

    docker build -t e2e-tests .

    docker run --rm e2e-tests

πŸ“Œ Notes

For headful testing or debugging, expose ports and use VNC tools.


Use --project=chromium or --reporter=html if needed.


Use --shm-size=1gb with Docker if you face browser crashes:


bash

Copy

Edit

docker run --shm-size=1gb --rm playwright-docker

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know