Run Headless Chrome Browser Inside a Docker Container

1. Overview

This is a simple example of how to config your own headless chrome browser inside a docker container. Then use a simple Python web application to say hello world with python selenium.

Project structure: - app.py - Dockerfile - bin/ + chromedriver + google-chrome-87_amd64.deb

Source code on GitHub

2. Coding

  • Dockerfile
FROM python:3.7

# Install manually all the missing libraries
RUN apt-get update
RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils
RUN apt-get install libgbm1 -y

# Install Chrome
COPY bin/chromedriver /usr/bin/chromedriver
COPY bin/google-chrome-87_amd64.deb .
RUN dpkg -i google-chrome-87_amd64.deb; apt-get -fy install

# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True
ENV PORT 5000

RUN pip install gunicorn

# Install Python dependencies.
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

# Copy local code to the container image.
COPY app.py /app/app.py
ENV APP_HOME /app
WORKDIR $APP_HOME


# Run the web service on container startup.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app
  • app.py
import os
from flask import Flask, send_file
import json
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
options.add_argument("--disable-gpu")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")

app = Flask(__name__)


@app.route('/', methods=['GET'])
def home():
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://www.google.com')
driver.save_screenshot("screenshot.png")

return send_file("screenshot.png", mimetype='image/png')


if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))

3. Test it

  • Build the docker image

docker build -t headless .

  • Run the docker container

docker run -it -p 5000:5000 headless