How to set up a Headless Chrome Node.js server in Docker
Tags: chrome, docker, node, tutorial
Published: 2020-01-14 20:03:43

---
title: How to set up a Headless Chrome Node.js server in Docker
published: true
date: 2020-01-10 17:00:30 UTC
tags: chrome,docker,node,tutorial
canonical_url: https://blog.logrocket.com/how-to-set-up-a-headless-chrome-node-js-server-in-docker/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/am8ufb5985f0vm2hlhbl.png
---
**Written by [Tigran Bayburtsyan](https://blog.logrocket.com/author/tigran-bayburtsyan/)**✏️

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](https://dev.to/bnevilleoneill/kubernetes-log-aggregation-eof).

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.

```jsx
const puppeteer = require('puppeteer');
const fs = require('fs');

Screenshot('https://google.com');

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.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## 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.

```jsx
FROM alpine:3.6

RUN apk update && apk add --no-cache nmap && \
    echo @edge http://nl.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
    echo @edge http://nl.alpinelinux.org/alpine/edge/main >> /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.

```jsx
// server.js
const express = require('express');
const puppeteer = require('puppeteer');

const app = express();

// /?url=https://google.com
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](https://hexometer.com/). 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 [browserless.io](https://www.browserless.io/) (there is an open-source version as well).

```jsx
...
...

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

...
...
```

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

## Conclusion

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](https://blog.logrocket.com/end-to-end-testing-react-apps-with-puppeteer-and-jest-ce2f414b4fd7/) 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.

* * *
## 200's only ‎✅: Monitor failed and show GraphQL requests in production 

While GraphQL has some features for debugging requests and responses, making sure GraphQL reliably serves resources to your production app is where things get tougher. If you’re interested in ensuring network requests to the backend or third party services are successful, [try LogRocket.](https://www2.logrocket.com/signup-lr)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jd2amkhuiynfjf3i33qk.png)

[LogRocket](https://www2.logrocket.com/signup-lr) 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 GraphQL requests to quickly understand the root cause. In addition, you can track Apollo client state and inspect GraphQL queries' key-value pairs.

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. [Start monitoring for free.](https://www2.logrocket.com/signup-lr)
* * *

The post [How to set up a Headless Chrome Node.js server in Docker](https://blog.logrocket.com/how-to-set-up-a-headless-chrome-node-js-server-in-docker/) appeared first on [LogRocket Blog](https://blog.logrocket.com).