乐闻世界logo
搜索文章和话题

How to run google chrome headless in docker?

1个答案

1

Running Google Chrome in headless mode within Docker is a common requirement, especially for automated testing or web scraping. Here are the steps to set up and run headless Chrome in Docker:

1. Create a Dockerfile

First, you need to create a Dockerfile to define your Docker image. This Dockerfile will include commands to install Chrome and its dependencies, along with other necessary packages. Here is a simple example:

Dockerfile
# Use the official Node.js as the base image FROM node:12-slim # Set the working directory WORKDIR /app # Install Chrome RUN apt-get update && apt-get install -y wget gnupg2 RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb RUN apt-get install -y ./google-chrome-stable_current_amd64.deb # Copy application files into the container COPY . /app # Install application dependencies RUN npm install # Start the application CMD ["node", "your-app.js"]

This Dockerfile starts with the Node.js image, suitable for applications requiring a Node.js environment. It downloads and installs the Chrome browser. Ensure the rest of your application is properly configured.

2. Build the Docker Image

After creating the Dockerfile, you can build the image using the following command:

bash
docker build -t your-image-name .

3. Run the Docker Container

Finally, you can run your Docker container with the following command, which launches Chrome in headless mode:

bash
docker run -d --name your-container-name your-image-name node your-app.js

In your Node.js application, you can use Puppeteer (a Node library that provides high-level APIs to control Chrome or Chromium) to launch Chrome in headless mode:

javascript
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: true, // Launch in headless mode args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({path: 'example.png'}); await browser.close(); })();

Conclusion

This setup allows you to run Google Chrome in headless mode within a Docker container. It is well-suited for automated testing and web scraping tasks, as it runs in an isolated environment without being affected by external factors.

2024年7月23日 13:36 回复

你的答案