User Agents

Web browsers and everyday web tech, explained

Fix Headless Chrome Errors in PM2: Complete Guide

· 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

Fixing headless Chrome errors in PM2 usually requires installing missing system dependencies, configuring the correct browser launch arguments to bypass sandbox restrictions, and ensuring the PM2 process manager has the correct environment paths to locate the Chrome binary. When running Puppeteer or Playwright via PM2 on a Linux server, the most common cause of failure is the absence of shared libraries that Chrome needs to render pages, leading to crashes or "failed to launch" errors that are often hidden in the standard PM2 logs.

What You'll Need

  • A Linux server (Ubuntu/Debian is most common) with Node.js installed.
  • PM2 installed globally via npm.
  • Sudo or root access to install system-level packages.
  • A Node.js project utilizing Puppeteer, Playwright, or Selenium.
  • Access to the terminal via SSH.

Step-by-Step

  1. Identify the Specific Error: PM2 often hides the detailed stack trace of a Chrome crash. To see exactly why Chrome is failing, stop the process and run your script manually using Node.js. Run node your-script.js. If you see an error like error while loading shared libraries: libatk-1.0.so.0: cannot open shared object file, you have a missing dependency issue. If you see a sandbox error, you have a permission issue.
  2. Install Missing System Dependencies: Headless Chrome is not just a Node package; it is a full browser that requires several Linux libraries to function. On Ubuntu or Debian, run the following command to install the most common requirements:

    sudo apt-get update && sudo apt-get install -y ca-certificates 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

    This ensures that the browser has the necessary graphics and system libraries to execute its rendering engine, even in headless mode.
  3. Configure Browser Launch Arguments: Linux environments, especially those running as root or within containers, often block the Chrome sandbox for security reasons. To fix this, you must pass specific flags to the browser launch configuration in your code. Update your Puppeteer or Playwright launch options as follows:

    const browser = await puppeteer.launch({ headless: "new", args: [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu" ] });

    The --no-sandbox flag is critical for PM2 processes running on many VPS providers. The --disable-dev-shm-usage flag prevents Chrome from crashing in environments with limited shared memory (like Docker or small RAM VPS), forcing it to use /tmp instead.
  4. Set the Chrome Executable Path: Sometimes PM2 cannot find the bundled Chromium binary. You can explicitly tell your application where the browser is located. First, find the path by running which google-chrome or which chromium-browser. Then, add the executablePath to your launch options:

    const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome-stable', args: ['--no-sandbox'] });
  5. Create a PM2 Ecosystem File: Instead of starting your app with a simple command, use an ecosystem.config.js file. This allows you to manage environment variables and memory limits which are often the cause of headless Chrome crashes.

    module.exports = { apps: [{ name: "chrome-bot", script: "index.js", env: { NODE_ENV: "production", PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: "false" }, max_memory_restart: "1G" }] };

    Setting max_memory_restart is vital because headless Chrome is notorious for memory leaks. PM2 will automatically restart the process if it exceeds the limit, preventing the entire server from freezing.
  6. Deploy and Monitor: Start your application using the ecosystem file: pm2 start ecosystem.config.js. Monitor the logs in real-time to ensure no new errors appear: pm2 logs chrome-bot. If the process restarts frequently, check the logs for "Out of Memory" errors.

Common Mistakes

One of the most frequent mistakes is forgetting to install the system dependencies and assuming that npm install puppeteer is sufficient. Puppeteer downloads the Chromium binary, but it does not install the Linux OS libraries required to run that binary. This leads to the frustrating "failed to launch" error that doesn't specify which library is missing.

Another common error is running the process as the root user without the --no-sandbox flag. Chrome's sandbox is designed to protect the user's system from malicious web content, but it requires a non-privileged user to operate. When PM2 runs a script as root, the sandbox fails to initialize, and the browser will not start unless the sandbox is explicitly disabled.

Developers also often overlook the /dev/shm partition. On many Linux distributions, the shared memory partition is too small for Chrome's heavy rendering processes. Failing to include --disable-dev-shm-usage often results in the browser crashing randomly after a few successful pages, which can be mistaken for a bug in the application logic rather than a system resource limitation.

Tips

To optimize performance, use the "new" headless mode (in Puppeteer) or the latest headless configuration. The older headless mode was a separate implementation from the full browser, whereas the new mode is the actual Chrome browser running without a UI, which provides better compatibility with modern websites and reduces "bot detection" triggers.

Implement a robust browser management strategy. Instead of launching a new browser instance for every single request, launch one browser and open new pages (tabs) for each task. This significantly reduces the CPU and RAM overhead on your server. Ensure you call await page.close() and await browser.close() in a finally block to prevent zombie Chrome processes from filling up your process table.

Use a custom user-agent string. Headless Chrome identifies itself as "HeadlessChrome" in the user-agent header, which is a red flag for many websites. Overriding this with a real browser string helps avoid 403 Forbidden errors and CAPTCHAs.

Troubleshooting

If your PM2 process is in a "looping" state (restarting every few seconds), the first step is to check the error logs using pm2 logs --lines 100. If the logs are empty or vague, redirect the stderr to a file in your ecosystem config: error_file: "./logs/err.log".

If you encounter a "Protocol error: Target closed" message, it usually means the Chrome process crashed internally. This is often caused by a memory leak or a site that is too heavy for the allocated RAM. Try increasing the server's swap space or reducing the number of concurrent pages being processed by your script.

If you are using a Docker container with PM2, ensure your Dockerfile includes the installation of the dependencies listed in Step 2. Additionally, you may need to add --disable-gpu to your launch arguments, as Docker containers typically do not have access to a GPU, and Chrome may waste resources attempting to initialize one.

Frequently Asked Questions

Why does Chrome work locally but fail in PM2 on my server?

Local machines (Windows/macOS) come with the necessary GUI libraries pre-installed. Linux servers are usually "stripped down" and lack the libraries (like libnss3 or libatk) that Chrome requires to render pages, even in headless mode.

Is it safe to use --no-sandbox in production?

Using --no-sandbox disables a layer of security. It is generally acceptable if you are only visiting trusted websites. However, if your bot visits untrusted, user-generated content, you should run the PM2 process under a dedicated, low-privilege Linux user instead of root.

How do I stop zombie Chrome processes from eating RAM?

Zombie processes occur when the Node.js process crashes before it can call browser.close(). You can clean these up manually using pkill -f chrome or by implementing a cron job that kills Chrome processes older than a certain age.

Does PM2's cluster mode work with headless Chrome?

Cluster mode can be tricky because each instance will launch its own Chrome browser. If you have 4 CPU cores and launch 4 instances, you will have 4 browsers running, which can quickly exhaust your RAM. It is often better to use fork mode and manage concurrency within your code.

How can I verify if the dependencies are correctly installed?

You can run ldd /path/to/chrome-binary. This command lists all the shared libraries the binary depends on and will explicitly mark any as "not found" if they are missing from the system.