User Agents

Web browsers and everyday web tech, explained

Run Headless Chrome with Puppeteer in AWS Lambda Docker

· 7 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

Running headless Chrome with Puppeteer in AWS Lambda requires a Docker container because the standard Lambda runtime environment lacks the necessary shared libraries and the Chromium binary required to render web pages. By packaging the application as a Docker image, you can install a specific version of Chromium and all its system-level dependencies (like ALPN, NSS, and Glibc) into the image, ensuring that the browser has a consistent environment to execute regardless of the underlying Lambda infrastructure. This approach bypasses the strict size limits of .zip deployments and provides the control needed to manage the complex dependencies of a headless browser.

What You'll Need

  • An AWS Account with permissions to use Lambda and Elastic Container Registry (ECR).
  • Docker installed and running on your local development machine.
  • Node.js installed locally for writing and testing your Puppeteer script.
  • AWS CLI configured with the necessary credentials to push images to ECR.
  • Basic familiarity with JavaScript and asynchronous programming (async/await).

Step-by-Step

  1. Initialize Your Project: Create a new directory for your project. Run npm init -y to create a package.json file. Install Puppeteer Core instead of the full Puppeteer package. Using npm install puppeteer-core is critical because you will provide the Chromium binary via the Docker image rather than letting Puppeteer download a version that may not be compatible with the Lambda Linux environment.
  2. Write the Lambda Handler: Create an index.js file. In this file, you must configure Puppeteer to launch with specific flags that allow it to run in a restricted container environment. You must set headless: "new" (or true) and include the --no-sandbox and --disable-setuid-sandbox flags. Without these flags, Chrome will fail to launch because the Lambda execution environment does not provide the necessary privileges for the Chrome sandbox. You should also point the executablePath to the location where Chromium will be installed in the Docker image, typically /opt/chrome/chrome or a path defined in your Dockerfile.
  3. Create the Dockerfile: This is the most critical step. You should start with the official AWS Lambda Node.js base image (e.g., public.ecr.aws/lambda/nodejs:18). You need to use yum install or apt-get (depending on the base image) to install the necessary libraries. Key dependencies usually include alsa-lib, atk, cups-libs, gtk3, libXcomposite, libXcursor, libXdamage, libXext, libXi, libXrandr, libXscrnsaver, libXtst, pango, and mesa-libgbm. After installing dependencies, you must download a version of Chromium that is compatible with the Amazon Linux version used by the base image. Many developers use a pre-compiled Chromium binary specifically built for Lambda to avoid build-time errors.
  4. Optimize the Docker Image: To keep the image size manageable, combine your RUN commands into a single layer. Clear the package manager cache (e.g., yum clean all) after installing dependencies. Copy your package.json and package-lock.json first, run npm install, and then copy the rest of your source code. This leverages Docker's layer caching, making subsequent builds much faster.
  5. Build and Tag the Image: Run the Docker build command: docker build -t puppeteer-lambda .. Once built, create a repository in AWS ECR. Authenticate your Docker client to ECR using the AWS CLI: aws ecr get-login-password --region region | docker login --username AWS --password-stdin account_id.dkr.ecr.region.amazonaws.com. Tag your image to match the ECR repository URI and push it using docker push.
  6. Configure the Lambda Function: Create a new Lambda function in the AWS Console and select "Container image" as the source. Select the image you just pushed to ECR. Crucially, increase the memory allocation. Puppeteer is resource-intensive; while it can run on 512MB, 1600MB to 3008MB is recommended to prevent "out of memory" crashes and to improve page load speeds, as Lambda scales CPU power proportionally to memory.
  7. Set Timeout and Environment Variables: Change the Lambda timeout from the default 3 seconds to something more realistic, such as 30 seconds or 1 minute. Headless browsers often take several seconds to launch and navigate. If your script requires specific API keys or target URLs, add these as environment variables in the Lambda configuration tab.

Common Mistakes

One of the most frequent errors is installing the full puppeteer package. This package automatically downloads a version of Chromium during npm install that is designed for the developer's local OS (like macOS or Windows), which will not run inside the Linux-based Lambda container. Always use puppeteer-core and manually manage the Chromium binary in the Dockerfile.

Another common mistake is forgetting the --no-sandbox flag. Chrome's sandbox is a security feature that requires specific kernel privileges that AWS Lambda does not grant to the user. If this flag is omitted, the browser will crash immediately upon launch with a "Failed to launch the browser process" error.

Many users also underestimate the memory requirements. If you see the function terminate abruptly without a clear JavaScript error, check the CloudWatch logs for "Task timed out' or 'Memory size exceeded'. A headless browser can easily spike in memory usage when loading heavy JavaScript frameworks or high-resolution images.

Tips

To improve performance, implement a singleton pattern for the browser instance. Instead of launching a new browser instance on every single Lambda invocation, declare the browser variable outside the handler function. This allows the browser to be reused across "warm" Lambda executions, significantly reducing the latency of subsequent requests by skipping the expensive browser startup phase.

Use page.setRequestInterception(true) to block unnecessary resources. By blocking images, CSS, and fonts, you can drastically reduce the amount of data transferred and the memory used by the browser. This is especially useful if you are only scraping text or performing API-based interactions.

For better debugging, set the DEBUG environment variable to puppeteer:*. This will print detailed logs of the Puppeteer internal process to CloudWatch, allowing you to see exactly where the browser is hanging or failing during the navigation process.

Troubleshooting

If you encounter the error Error: Failed to launch the browser process!, the first thing to check is the executablePath. Ensure that the path provided in your JavaScript code exactly matches the location where Chromium was installed in the Docker image. If the path is correct, verify that all shared library dependencies are present. You can debug this by adding a command to your Dockerfile or a temporary Lambda function that runs ldd /path/to/chrome; this will list all missing shared libraries (marked as "not found").

If the function times out consistently, check if the website you are visiting has bot detection. Some sites detect headless Chrome and hang the connection or present a CAPTCHA. Try setting a realistic User-Agent string in your Puppeteer launch options to mimic a real browser. You can find current User-Agent strings from actual browsers to avoid being flagged as a bot.

In cases where the Docker image is too large to push or deploy, ensure you are using a slim base image and that you are not copying node_modules from your local machine into the image. Use a .dockerignore file to exclude node_modules and local environment files, forcing the image to build its own dependencies from scratch.

Frequently Asked Questions

Why can't I just use a Lambda Layer for Chromium?

While Layers are possible, Chromium and its dependencies often exceed the 250MB unzipped limit of Lambda Layers. Docker images allow up to 10GB, making them the reliable choice for browser binaries.

Does Puppeteer work with the Lambda "arm64" architecture?

It can, but you must ensure the Chromium binary you download is compiled for ARM64. Most pre-built Lambda Chromium binaries are for x86_64, so it is safer to stick to the x86_64 architecture for the Lambda function configuration.

How do I handle PDF generation in this setup?

Puppeteer's page.pdf() method works in this environment. However, ensure you have enough memory allocated, as rendering a PDF is more resource-intensive than taking a screenshot or scraping HTML.

Can I run multiple browser tabs simultaneously?

Yes, you can use browser.newPage() to open multiple tabs. However, be cautious of memory usage; each new tab increases the RAM consumption, which can lead to the Lambda function being killed.

How do I handle authentication or cookies?

You can use page.setCookie() to inject session cookies or use page.type() and page.click() to perform a login flow. Since Lambda is stateless, you will need to store these cookies in a database like DynamoDB if you want to persist sessions across different invocations.