How to set up a Headless Chrome Node.js server in Docker - LogRocket Blog

January 10, 2020 0 Comments

How to set up a Headless Chrome Node.js server in Docker - LogRocket Blog



Headless browsers have become very popular with the rise of automated UI tests in the application development process. There are also countless use cases for website crawlers and HTML-based content analysis.

For 99 percent of these cases, you don’t actually need a browser GUI because it is fully automated. Running a GUI is more expensive than spinning up a Linux-based server or scaling a simple Docker container across a microservices cluster such as Kubernetes.

But I digress. Put simply, it has become increasingly critical to have a Docker container-based headless browser to maximize flexibility and scalability. In this tutorial, we’ll demonstrate how to create a Dockerfile to set up a Headless Chrome browser in Node.js.

Headless Chrome with Node.js

Node.js is the main language interface used by the Google Chrome development team, and it has an almost native integrated library for communicating with Chrome called Puppeteer.js. This library uses WebSocket or a System Pipe-based protocol over a DevTools interface, which can do all kinds of things such as take screenshots, measure page load metrics, connection speeds, and downloaded content size, and more. You can test your UI on different device simulations and take screenshots with it. Most importantly, Puppeteer doesn’t require a running GUI; it can all be done in a headless mode.

const puppeteer = require('puppeteer');
const fs = require('fs'); Screenshot(''); async function Screenshot(url) { const browser = await puppeteer.launch({ headless: true, args: [ "--no-sandbox", "--disable-gpu", ] }); const page = await browser.newPage(); await page.goto(url, { timeout: 0, waitUntil: 'networkidle0', }); const screenData = await page.screenshot({encoding: 'binary', type: 'jpeg', quality: 30}); fs.writeFileSync('screenshot.jpg', screenData); await page.close(); await browser.close();

Shown above is the simple actionable code for taking a screenshot over Headless Chrome. Note that we are not specifying Google Chrome’s executable path because Puppeteer’s NPM module comes with a Headless Chrome version embedded inside. Chrome’s dev team did a great job of keeping the library usage very simple and minimizing the required setup. This also makes our job of embedding this code inside the Docker container much easier.

Google Chrome inside a Docker container

Running a browser inside a container seems simple based on the code above, but it’s important not to overlook security. By default, everything inside a container runs under the root user, and the browser executes JavaScript files locally.

Of course, Google Chrome is secure, and it doesn’t allow users to access local files from browser-based script, but there are still potential security risks. You can minimize many of these risks by creating a new user for the specific purpose of executing the browser itself. Google also has sandbox mode enabled by default, which restricts external scripts from accessing the local environment.

Below is the Dockerfile sample responsible for the Google Chrome setup. We will choose Alpine Linux as our base container because it has a minimal footprint as a Docker image.

FROM alpine:3.6 RUN apk update && apk add --no-cache nmap && \ echo @edge >> /etc/apk/repositories && \ echo @edge >> /etc/apk/repositories && \ apk update && \ apk add --no-cache \ chromium \ harfbuzz \ "freetype>2.8" \ ttf-freefont \ nss ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true ....

The run command handles the edge repository for getting Chromium for Linux and libraries required to run chrome for Alpine. The tricky part is to make sure we don’t download Chrome embedded inside Puppeteer. That would be a useless space for our container image, which is why we are keeping the PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true environment variable.

After running the Docker build, we get our Chromium executable: /usr/bin/chromium-browser. This should be our main Puppeteer Chrome executable path.

Now let’s jump to our JavaScript code and complete a Dockerfile.

Combining Node.js Server and Chromium container

Before we continue, let’s change a little bit of our code to fit as a microservice for taking screenshots of given websites. For that, we’ll use Express.js to spin a basic HTTP server.

// server.js
const express = require('express');
const puppeteer = require('puppeteer'); const app = express(); // /?url=
app.get('/', (req, res) => { const {url} = req.query; if (!url || url.length === 0) { return res.json({error: 'url query parameter is required'}); } const imageData = await Screenshot(url); res.set('Content-Type', 'image/jpeg'); res.set('Content-Length', imageData.length); res.send(imageData);
}); app.listen(process.env.PORT || 3000); async function Screenshot(url) { const browser = await puppeteer.launch({ headless: true, executablePath: '/usr/bin/chromium-browser', args: [ "--no-sandbox", "--disable-gpu", ] }); const page = await browser.newPage(); await page.goto(url, { timeout: 0, waitUntil: 'networkidle0', }); const screenData = await page.screenshot({encoding: 'binary', type: 'jpeg', quality: 30}); await page.close(); await browser.close(); // Binary data of an image return screenData;

This is the final step to complete a Dockerfile. After running docker build -t headless:node, we’ll have an image with Node.js service and a Headless Chrome browser for taking screenshots.

Taking screenshots is fun, but there are countless other use cases. Fortunately, the process described above applies to almost all of them. For the most part, only minor changes to the Node.js code would be required. The rest is pretty standard environmental setup.

Common problems with Headless Chrome

Google Chrome eats a lot of memory during execution, so it’s no surprise that Headless Chrome does the same on the server side. If you keep a browser open and reuse the same browser instance many times, your service will eventually crash.

The best solution is to follow the principle of one connection, one browser instance. While this is more expensive than managing multiple pages per browser, sticking to just one page and one browser will make your system more stable. Of course, this all depends on personal preference and your particular use case. Depending on your unique needs and goals, you may be able to find a middle ground.

Take, for example, the official website for performance monitoring tool Hexometer. The environment includes a remote browser service that contains hundreds of idle browser pools. These are designed to pick up new connections over WebSocket when there is a need for execution, but it strictly follows the principle of one page, one browser. This makes it a stable and efficient way to not only keep running browsers idle, but keep them alive.

Puppeteer connection over WebSocket is pretty stable, and you can do something similar by making a custom service like (there is an open-source version as well).

... const browser = await puppeteer.launch({ browserWSEndpoint: `ws://`,
}); ...

This will connect to the headless Chrome DevTools socket using the same browser management protocol.


Having a browser running inside a container provides a lot of flexibility and scalability. It’s also a lot cheaper than traditional VM-based instances. Now we can simply use a container service such as AWS Fargate or Google Cloud Run to trigger container execution only when we need it and scale to thousands of instances within a seconds.

The most common use case is still making UI automated tests with Jest and Mocha. But if you consider that you can actually manipulate a full webpage with Node.js inside a container, the use cases are limited only by your imagination.

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .

Tag cloud