Asmit Karmakar
Asmit Karmakar

Reputation: 145

Playwright Launch Persistent Context doesn't work in Docker

Background: I have a chromium user-data folder which contains a logged-in Instagram account. I want playwright to launch using persistent context from the user-data folder, open Instagram, and take a screenshot.

Problem: This works fine locally, but when I try to build a Docker container and run the script, it no longer remains logged in, as the screenshot shows.

Directory Structure:

Insta Docker Test/
│-- Dockerfile
│-- main.py
└-- playwright_data/      # User Data Folder

Code:

main.py

import os
import time
from playwright.sync_api import sync_playwright
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
user_dir = os.path.join(os.getcwd(), "playwright_data")
with sync_playwright() as p:
    # Launch Chrome browser with persistent context and extension
    browser = p.chromium.launch_persistent_context(
        user_data_dir=user_dir,  # explicitly specify this as a keyword argument
        channel="chrome",
        user_agent=ua,
    )
    page = browser.new_page()
    page.goto("https://www.instagram.com/" , timeout=300000)
    page.wait_for_load_state("networkidle", timeout=300000)
    page.screenshot(path="screenshot.png")
    time.sleep(300000)

Dockerfile

FROM python:3.12.4
WORKDIR /app
COPY . /app
RUN pip install pytest-playwright
RUN playwright install chrome
CMD ["python", "main.py"]

Attempts at fixing:

I think that since it is working locally, changing Dockerfile appropriately might work. But so far, I haven't been able to.

How to reproduce:

  1. Make the directory structure and copy the code. Keep playwright_data empty.
  2. In main.py, add a line headless=False, after user_agent=ua,
  3. Open Terminal and run python main.py
  4. A browser will appear and open Instagram. Login to your profile. Then close the browser and close the terminal.
  5. Remove the line of code you added in step 2.
  6. Now it is ready. Run locally and in docker to see the difference.

Thanks!

Upvotes: 0

Views: 41

Answers (0)

Related Questions