Docker Image for Karma Tests with Headless Chrome
In this article
This guide walks you through creating a Docker image that runs Karma unit tests using Headless Chrome. By containerizing your test environment, you ensure consistent browser behavior across all developer machines and CI servers, eliminating the classic "works on my machine" problem. You'll end up with a reusable Dockerfile that installs Node.js, Chrome, and your project dependencies, then runs your Karma test suite headlessly.
What You'll Need
- A project with a
package.jsonthat includes Karma and a Karma configuration file (e.g.,karma.conf.js). - Docker installed on your machine (version 20.10 or later recommended).
- Basic familiarity with the command line.
Step-by-Step
- Review your Karma configuration. Ensure your
karma.conf.jsuses theChromeHeadlesslauncher. If not, installkarma-chrome-launcherand setbrowsers: ['ChromeHeadless']. Also setsingleRun: trueso tests exit after completion. - Create a Dockerfile in your project root. Start with a Node.js base image, for example
FROM node:18-slim. This gives you a minimal Linux environment with Node and npm. - Install Chromium and dependencies. Headless Chrome needs certain system libraries. Add the following to your Dockerfile:
RUN apt-get update && apt-get install -y \ chromium \ fonts-liberation \ libappindicator3-1 \ libasound2 \ libatk-bridge2.0-0 \ libatk1.0-0 \ libcups2 \ libdbus-1-3 \ libgdk-pixbuf2.0-0 \ libnspr4 \ libnss3 \ libx11-xcb1 \ libxcomposite1 \ libxdamage1 \ libxrandr2 \ xdg-utils \ --no-install-recommendsOn Debian-based images, the package is namedchromium(notgoogle-chrome). - Set environment variables to tell Chrome to run in headless mode and to avoid sandbox issues in containers. Add:
ENV CHROME_BIN=/usr/bin/chromium ENV CI=true
TheCHROME_BINvariable tells Karma which Chrome binary to use. TheCIvariable makes Karma run in CI mode (which implies single run). - Copy your package files and install dependencies. This leverages Docker layer caching:
WORKDIR /app COPY package*.json ./ RUN npm install
If you use npm ci for exact versions, replace the RUN line withRUN npm ci. - Copy the rest of your source code. Add
COPY . .to bring in your tests, source, and Karma config. - Define the command to run tests. Add:
CMD ["npm", "test"]
This assumes yourpackage.jsonhas a"test"script that runs Karma (e.g.,"test": "karma start --single-run"). Adjust if needed. - Build the image. From your project root, run:
docker build -t karma-tests .
This creates an image taggedkarma-tests. - Run the container. Execute:
docker run --rm karma-tests
The--rmflag removes the container after it finishes, keeping your system clean. You should see Karma output and a success/failure summary.
Common Mistakes
- Forgetting to set CHROME_BIN – Karma will not find Chrome and will throw a launcher error.
- Using the wrong package name – On Debian/Ubuntu, it's
chromium, notgoogle-chrome-stable. Using the latter will cause apt-get to fail. - Not installing all required system libraries – Chrome may crash with missing shared libraries. The list in Step 3 covers common ones, but if you get errors, add the missing packages.
- Running with sandbox enabled – Chrome's sandbox often fails in Docker. You must either set the
--no-sandboxflag in your Karma config or use theCHROME_BINenvironment variable as shown. The simplest is to addcustomLaunchersin Karma config:customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } }Then setbrowsers: ['ChromeHeadlessNoSandbox'].
Tips
- Use a specific Node version – Pinning to a major version (e.g.,
node:18-slim) ensures reproducibility. Avoidlatesttags. - Leverage Docker layer caching – Copy
package.jsonandpackage-lock.jsonbefore your source code so npm install only runs when dependencies change. - Add a .dockerignore file – Exclude
node_modules,.git, and other unnecessary files to speed up builds and reduce image size. - Use multi-stage builds for smaller images – If you need to keep the image small, consider a multi-stage build where you install dependencies in one stage and copy only the necessary artifacts to a fresh stage.
- Run tests with
--rmand--volumefor live development – You can mount your source code into the container:docker run --rm -v $(pwd):/app karma-teststo test changes without rebuilding the image.
Troubleshooting
- Error: "Chrome failed to start" – Check that
CHROME_BINpoints to the correct binary. Runwhich chromiuminside the container to verify. Also ensure all system libraries are installed. - Error: "Missing X server or $DISPLAY" – This usually means Chrome is trying to run in headed mode. Make sure you're using
ChromeHeadlessand thatCI=trueis set. - Error: "Could not find the binary 'google-chrome'" – You're using the wrong launcher or the wrong binary name. Set
CHROME_BIN=/usr/bin/chromiumor update your Karma config to use the correct custom launcher. - Tests run but hang – This often happens when Karma is not set to
singleRun. SetsingleRun: truein your config, or pass--single-runin your npm test script. - Permission denied errors – If you see EACCES errors, ensure your container user has write access to the working directory. You can run the container with
--user $(id -u):$(id -g)to match your host user.
Frequently Asked Questions
Can I use Google Chrome instead of Chromium?
Yes, but you'd need to install the proprietary Google Chrome .deb package, which requires downloading from Google's servers. Chromium is open-source and available in Debian's repositories, making it easier and more license-friendly for CI.
Why do I need to add --no-sandbox?
Chrome's sandbox relies on kernel features that are often disabled in Docker containers. Without the flag, Chrome may crash or refuse to run. It's a common and accepted workaround for containerized testing.
How do I pass environment variables to my tests?
Use the -e flag with docker run, e.g., docker run -e MY_VAR=value karma-tests. Your tests can read them via process.env.
Can I use this image for other Node.js tasks?
Yes, the image includes Node.js and npm, so you can run any Node command by overriding the default command, e.g., docker run karma-tests node -v.
How do I debug failing tests inside the container?
Run the container interactively with docker run -it karma-tests /bin/bash. Then you can manually run npm test and inspect the environment. You can also mount your source code with -v to edit files live.
What if my tests need a database or other services?
You can use Docker Compose to define multiple services (e.g., a database container) and run your test container alongside them. Or you can use the --network flag to connect to an existing network.