User Agents

Web browsers and everyday web tech, explained

Fix Puppeteer Browser Disconnected Errors in Docker

· 6 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To fix Puppeteer "browser has disconnected" errors in Docker, you must primarily address shared memory limitations and missing system dependencies. The most common cause is the default Docker shared memory size (64MB), which is insufficient for Chromium's rendering engine, leading to sudden crashes. By adding the --disable-dev-shm-usage flag to your Puppeteer launch configuration and increasing the container's shared memory via --shm-size=2gb in your Docker run command or Compose file, you can stabilize the browser connection.

What You'll Need

  • A Docker environment (Docker Desktop or Docker Engine) installed on your machine.
  • A Node.js project utilizing the puppeteer or puppeteer-core library.
  • Administrative access to modify the Dockerfile and docker-compose.yml (if applicable).
  • Basic knowledge of JavaScript/TypeScript for updating the browser launch arguments.

Step-by-Step

  1. Modify the Puppeteer Launch Configuration: The first and most critical step is to tell Chromium not to use /dev/shm for shared memory. By default, Chromium uses this partition for its internal memory management. In Docker, this partition is too small, causing the browser to crash and disconnect. Update your puppeteer.launch() call to include the following arguments:
    const browser = await puppeteer.launch({
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-gpu'
      ],
      executablePath: '/usr/bin/google-chrome-stable' // Path may vary by OS
    });
    The --disable-dev-shm-usage flag forces Chromium to use /tmp instead of /dev/shm, which prevents the memory-related crashes that trigger the disconnection error.
  2. Increase Docker Shared Memory: While the flag above helps, increasing the actual shared memory allocated to the container is a more robust solution for high-traffic applications. If you are using the Docker CLI, add the --shm-size flag:
    docker run --shm-size=2gb my-puppeteer-app
    If you are using Docker Compose, add the shm_size property to your service definition:
    services:
      app:
        build: .
        shm_size: '2gb'
    Setting this to 2GB ensures that even complex pages with many assets can be rendered without exhausting the allocated memory.
  3. Install Necessary System Dependencies: The "disconnected" error often occurs when the browser attempts to execute a function but fails because a low-level Linux library is missing. You must ensure your Dockerfile installs all required dependencies for Chromium. Add the following block to your Dockerfile (assuming a Debian/Ubuntu base):
    RUN apt-get update && apt-get install -y \
          fonts-liberation \
          libasound2 \
          libatk-bridge2.0-0 \
          libatk1.0-0 \
          libc6 \
          libcairo2 \
          libcups2 \
          libdbus-1-3 \
          libexpat1 \
          libfontconfig1 \
          libgbm1 \
          libgcc1 \
          libglib2.0-0 \
          libgtk-3-0 \
          libnspr4 \
          libnss3 \
          libpango-1.0-0 \
          libpangocairo-1.0-0 \
          libstdc++6 \
          libx11-6 \
          libx11-xcb1 \
          libxcb1 \
          libxcomposite1 \
          libxcursor1 \
          libxdamage1 \
          libxext6 \
          libxfixes3 \
          libxi6 \
          libxrandr2 \
          libxrender1 \
          libxss1 \
          libxtst6 \
          lsb-release \
          wget \
          xdg-utils
    Without these, the browser may start but crash immediately upon navigating to a page, resulting in a disconnection error.
  4. Handle Zombie Processes: Docker containers often struggle with PID 1. When Puppeteer launches Chromium, it creates child processes. If the main Node.js process doesn't reap these children, you end up with "zombie" processes that consume resources and eventually cause the browser to disconnect or the container to hang. Use a lightweight init system like tini. Update your Dockerfile:
    RUN apt-get update && apt-get install -y tini
    ENTRYPOINT ["/usr/bin/tini", "--", "node", "index.js"]
    Tini ensures that signals (like SIGTERM) are passed correctly to Chromium and that defunct processes are cleaned up.
  5. Implement Robust Error Handling and Retries: Even with a perfect setup, network glitches or memory spikes can cause a disconnection. Wrap your browser logic in a try-catch block and implement a retry mechanism. Instead of letting the app crash, catch the Error: Protocol error (Runtime.callFunctionOn): Target closed and restart the browser instance.

Common Mistakes

  • Using the default puppeteer.launch() without arguments: Many developers assume the default settings work in Docker. However, the --no-sandbox flag is almost always required because Docker containers run as root by default, and Chromium's sandbox requires a user namespace that isn't present in standard containers.
  • Forgetting to clean up browser instances: Calling browser.close() is mandatory. If you leave browser instances open in a loop, you will quickly exhaust the container's RAM, leading to a crash and the subsequent "browser has disconnected" error.
  • Using puppeteer-core without a matching browser version: If you use puppeteer-core to save space, you must manually install Chromium. If the version of the installed Chromium does not match the version expected by the library, the connection will be unstable.
  • Ignoring the /dev/shm limit: Some developers try to fix the issue by simply adding more RAM to the Docker Desktop settings. While this increases the overall memory, it does not increase the specific /dev/shm partition size, which is the root cause of the crash.

Tips

  • Use a Headless Shell: If you are using the latest version of Puppeteer, try headless: 'new'. The new headless mode is more consistent with the actual Chrome browser and often handles memory more efficiently.
  • Optimize Page Loading: To reduce memory pressure, disable unnecessary assets. Use page.setRequestInterception(true) to block images, CSS, and fonts if you only need the HTML content. This significantly reduces the likelihood of the browser crashing.
  • Monitor Container Memory: Use docker stats while your script is running. If you see the memory usage climbing steadily without dropping, you likely have a memory leak in your page handling logic, which will eventually lead to a disconnection.
  • Alpine Linux Warning: While Alpine images are smaller, they use musl libc instead of glibc. Chromium requires glibc. While there are ways to make it work, using a Debian-based slim image (e.g., node:slim) is generally more stable for Puppeteer.

Troubleshooting

If you have applied the steps above and still encounter disconnection errors, follow this diagnostic path:

Check the Docker Logs: Run docker logs [container_id]. Look for "Out of Memory" (OOM) errors. If you see oom-kill in the system logs, your container is exceeding its hard memory limit, and you need to increase the RAM allocated to Docker or optimize your script.

Verify Browser Path: Ensure that the executablePath provided in the launch options is exactly where the browser is installed. Run docker exec -it [container_id] which google-chrome-stable to verify the path. An incorrect path can sometimes cause the launcher to fail silently or crash immediately after start.

Test with a Simple Page: Try navigating to about:blank. If the browser stays connected to a blank page but disconnects on a real website, the issue is likely the complexity of the website (heavy JS/CSS) exhausting the memory, rather than a configuration error. This confirms that you need more shm_size.

Check for Version Mismatch: Ensure your package.json Puppeteer version matches the Chromium version installed in the OS. If you are using apt-get install chromium-browser, check the version with chromium-browser --version and ensure the Puppeteer library is compatible.

Frequently Asked Questions

Why is --no-sandbox necessary in Docker?

Chromium uses a sandbox to isolate the browser process from the rest of the system for security. This sandbox requires specific Linux kernel privileges (user namespaces) that are disabled by default in Docker containers. --no-sandbox disables this feature, allowing the browser to run as the root user inside the container.

Does --disable-dev-shm-usage slow down the browser?

There is a negligible performance hit because the browser uses /tmp (disk/virtual memory) instead of /dev/shm (RAM). For most scraping or automation tasks, this difference is imperceptible and is a necessary trade-off for stability in Docker.

Can I use a non-root user to avoid --no-sandbox?

Yes. If you create a dedicated user in your Dockerfile and assign the correct permissions to the Chromium installation folder, you can run the browser without --no-sandbox. This is the recommended approach for production environments to improve security.

How much shm_size is actually enough?

For simple page scraping, 256MB to 512MB is often sufficient. However, for rendering heavy Single Page Applications (SPAs) or generating large PDFs, 2GB is the industry standard to ensure the browser does not crash during heavy rendering cycles.

Will these fixes work for Puppeteer-core?

Yes, these fixes are related to the Chromium binary and the Docker environment, not the Puppeteer wrapper. Whether you use puppeteer (which bundles Chromium) or puppeteer-core (which uses an external browser), the memory and dependency requirements remain the same.