如何在 Docker 容器内使用 Puppeteer
介绍
Puppeteer是一个 Node.js 库,它提供了一个高级 API,可以通过 DevTools 协议控制 Chromium(或 Firefox)浏览器。
本指南将帮助您在 Docker 容器中使用 Node.js 镜像来使用Puppeteer 。
如果我们使用 Node.js v14 LTS Gallium 的 Docker 镜像,从该镜像安装chromium软件包时apt,版本将是 v90.0,这可能与最新的 Puppeteer 存在兼容性问题。这是因为该软件包是使用最新的 Chromium 稳定版进行测试的。
选择正确的图像
嗯……我们想在容器内运行一个网页浏览器。了解不同版本之间的区别很重要。
阿尔卑斯山就足够了,但是……
是的,我们可以在 Alpine Linux 上运行 Chromium,但需要一些额外的步骤才能运行。所以我们更倾向于使用 Debian 的衍生版本,这样更方便。
哪个发行版?
每个主要的 Node.js 版本都是基于 Debian 版本构建的,而该 Debian 版本又自带一个旧版本的 Chromium,该版本可能与最新版本的 Puppeteer 不兼容。
| Node.js | Debian | 铬 |
|---|---|---|
| v14 | 9.13 | 73.0.3683.75 |
| v16 | 10.9 | 90.0.4430.212 |
| v17 | 11.2 | 99.0.4844.84 |
为了快速解决这个问题,我们可以使用谷歌 Chrome 的 Debian 软件包,它始终安装最新的稳定版本。因此,此 Dockerfile 与 Node.js v14、v16 或任何更新的版本都兼容。
为什么不使用内置的铬呢?
安装谷歌浏览器时,apt它会自动安装所有依赖项。
Dockerfile
FROM node:slim AS app
# We don't need the standalone Chromium
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true
# Install Google Chrome Stable and fonts
# Note: this installs the necessary libs to make the browser work with Puppeteer.
RUN apt-get update && apt-get install curl gnupg -y \
&& curl --location --silent https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install google-chrome-stable -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# Install your app here...
💡 如果您使用的是像 Apple M1 这样的基于 ARM 的 CPU,则--platform在构建 Docker 镜像时应该使用该参数。
docker build --platform linux/amd64 -t image-name .
代码配置
请记住,在应用程序代码中,要使用已安装的浏览器,而不是 Puppeteer 内置的浏览器。
import puppeteer from 'puppeteer';
...
const browser = await puppeteer.launch({
executablePath: '/usr/bin/google-chrome',
args: [...] // if we need them.
});
结论
通过 apt 安装浏览器会自动解析在 Docker 容器内运行无头浏览器所需的依赖项,无需任何手动干预。这些依赖项默认情况下并未包含在 Node.js Docker 镜像中。
在 Docker 容器中使用 Puppeteer 的最简单方法是安装 Google Chrome,因为与 Debian 提供的 Chromium 软件包不同,Chrome 只提供最新的稳定版本。
更新于 2022 年 8 月 24 日
这个新的 Dockerfile 版本
FROM node:slim
# We don't need the standalone Chromium
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true
# Install Google Chrome Stable and fonts
# Note: this installs the necessary libs to make the browser work with Puppeteer.
RUN apt-get update && apt-get install gnupg wget -y && \
wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
apt-get update && \
apt-get install google-chrome-stable -y --no-install-recommends && \
rm -rf /var/lib/apt/lists/*
应用以下更改:
A. 移除apt-key弃用警告。
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
B. 之所以使用它,wget是因为它是由安装程序安装的google-chrome-stable,而且它减少了几个 MiB 的安装空间curl。