How to Run Headless Nightmarejs in a Docker Container

If you need to run Nightmare.js tests inside a docker container for CI/CD or a web scraping/web automation cron job you will notice that electron (what nightmare.js uses) won’t simply run in the container since the headless container is missing various UI libraries (as it should) that electron needs. After research and trial-and-error, I got it to work. I lay it out here in the hopes that it saves someone some time someday - “Future Zach” at least :).

Here is a quick setup to be able to run headless Nightmare.js scripts inside a Docker container.

You can either grab from my repo and try it like so:

1
2
3
4
5
6
@zacharykeeton:~$ git clone https://gitlab.com/zacharykeeton/dockersnightmare.git
@zacharykeeton:~$ cd dockersnightmare/
@zacharykeeton:~/dockersnightmare$ docker build --tag nightmaretest .
... [docker build output snipped] ...
@zacharykeeton:~/dockersnightmare$ docker run nightmaretest
DuckDuckGo — Privacy, simplified.

Or you can walk through the steps yourself (below).

4 Steps to Get Nightmare.js Running in a Container

1. Create node project

1
2
3
4
5
$ mkdir nightmareTest
$ cd nightmareTest
$ npm init -y
$ npm install --save nightmare
$ vim nightmareTest.js

in nightmareTest.js enter the following:

1
2
3
4
5
6
7
8
9
10
11
12
const Nightmare = require('nightmare');

const nightmare = Nightmare();

nightmare.goto('https://duckduckgo.com/')
.evaluate(() => {
return document.title;
})
.end()
.then((title) => {
console.log(title);
});

2. Create Dockerfile

In the same directory, add the Dockerfile:

1
$ vim Dockerfile

with text:

1
2
3
4
5
6
7
8
9
10
11
12
FROM node:10.15.3

WORKDIR /usr/src/app

COPY . .

RUN apt-get update && \
apt-get -y install libxss1 libxtst6 libgconf-2-4 libnss3 libasound2 xvfb && \
npm install -g xvfb-maybe && \
npm install

CMD ["xvfb-maybe", "node", "nightmareTest.js"]

All the libs and xvfb (virtual frame buffer) enable electron to run in the container (a nightmarejs dependency). The xvfb-maybe sets up the environment for the electron app to work. Getting the right libs and config is what took the most time to get working. You’re welcome :)

3. Build New Docker Image

Then:

1
$ docker build --tag nightmareTest .

4. Run Your New Image

1
$ docker run --rm nightmareTest

The --rm flag will remove (and not just stop) the container one the process exits.

GET RESULTS!

1
"DuckDuckGo — Privacy, simplified."
Share