Run chromedp with Chrome Headless Shell in Docker
In this article
Running chromedp with the Chrome Headless Shell in Docker allows you to automate browser interactions in a lightweight, isolated environment. By using the specialized "headless-shell" binary instead of the full Chrome browser, you reduce the image size and resource overhead while maintaining the ability to scrape data, generate PDFs, or perform automated testing. This setup ensures that your Go application has a consistent browser environment regardless of where the container is deployed.
What You'll Need
- Go installed on your local development machine (1.18 or later recommended).
- Docker installed and running.
- A basic understanding of Dockerfiles and containerization.
- The
chromedpGo package integrated into your project.
Step-by-Step
- Initialize your Go project: Create a new directory for your project and initialize your module. Install the chromedp package using
go get -u github.com/chromedp/chromedp. - Write the Go automation code: Create a
main.gofile. Ensure that your chromedp allocator is configured to handle the Docker environment. Specifically, you must disable the sandbox and use the--headless=newor--headless=oldflag. Example configuration:opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.NoSandbox, chromedp.DisableGPU). - Create a multi-stage Dockerfile: Use a multi-stage build to keep the final image small. The first stage should be a Go build environment (e.g.,
golang:1.21-alpine), and the second should be a runtime environment that includes the Chrome Headless Shell. - Install Chrome Headless Shell in the Dockerfile: In your runtime stage, you need to install the
chromium-headless-shellpackage. On Alpine Linux, this can often be achieved via the community repositories. If using Debian-based images, you may need to download the specific headless-shell binary from the Google Chrome for Testing (CfT) endpoints. - Configure User Permissions: Chrome cannot run as the root user without the
--no-sandboxflag. While--no-sandboxis common in Docker, it is safer to create a non-privileged user in your Dockerfile usingRUN adduser -D chromeuserand switching to that user withUSER chromeuser. - Set the Executable Path: In your Go code, tell chromedp exactly where the headless shell binary is located. Use
chromedp.ExecPath("/usr/bin/chromium-headless-shell")(adjust the path based on your installation) within your allocator options. - Build the Docker image: Run
docker build -t chromedp-headless .in your terminal. - Run the container: Execute the container using
docker run --rm chromedp-headless. If your application requires significant memory for heavy pages, consider adding the--shm-size=2gbflag to prevent the browser from crashing due to insufficient shared memory.
Common Mistakes
- Forgetting --no-sandbox: Attempting to run Chrome as root without the
--no-sandboxflag will result in an immediate crash. - Ignoring /dev/shm: Docker containers default to a small shared memory size (64MB). Chrome uses this for rendering; if it runs out, the browser will crash with an "Aw Snap!" error.
- Using the full Chrome binary: Installing the full Google Chrome browser instead of the Headless Shell increases image size by hundreds of megabytes without providing any benefit for headless automation.
- Mismatching Versions: Using a version of chromedp that is incompatible with the installed version of the Headless Shell. Always keep both updated.
Tips
- Use Chrome for Testing (CfT): Use the official Google "Chrome for Testing" binaries to ensure you have a version specifically designed for automation that doesn't auto-update unexpectedly.
- Optimize Image Size: Use
alpineas your base image for the runtime stage to keep the deployment footprint minimal. - Log Browser Output: Use
chromedp.WithLogfto pipe browser logs to your container's stdout, making it much easier to debug failures in a headless environment. - Zombie Process Management: Use
--initwhen running your docker container (docker run --init) to ensure that zombie Chrome processes are properly reaped.
Troubleshooting
If the container exits immediately or the Go program hangs, check the following:
- Check for Missing Dependencies: Chrome requires several system libraries (like
nss,freetype, andglib). If using a slim image, ensure all required shared libraries are installed viaapk addorapt-get install. - Verify Binary Path: Run to confirm the binary is actually where your Go code expects it to be.
- Inspect Logs: If you see "context deadline exceeded," increase the timeout in your Go code. Headless browsers in Docker can be slower to start than on a native OS.
- Memory Limits: If the browser crashes on complex pages, increase the Docker memory limit or use
--disable-dev-shm-usagein your chromedp options to force Chrome to use/tmpinstead of/dev/shm.
Frequently Asked Questions
What is the difference between Chrome and Chrome Headless Shell?
Chrome Headless Shell is a stripped-down version of the browser that removes the browser UI and unnecessary features, making it faster and smaller for automation tasks.
Do I really need --no-sandbox in Docker?
Yes, unless you configure a complex seccomp profile or run as a non-root user with specific capabilities, Chrome's sandbox will fail to initialize inside a standard Docker container.
How do I handle CAPTCHAs in a headless Docker environment?
Headless browsers are easily detected. To reduce detection, use a realistic User-Agent string and avoid using the default "HeadlessChrome" identifier in the navigator object.
Can I run multiple browser instances in one container?
Yes, but you must manage separate user data directories for each instance using chromedp.UserDataDir to avoid profile locking conflicts.
Why is my Docker image so large?
Browser binaries are inherently large. Using a multi-stage build and the Headless Shell instead of the full browser is the most effective way to minimize size.