最近有个需求,要制作某些网页渲染完成的缩略图,最后用Puppeteer完成了任务,这里记一下Docker方案,以备后用。

 

1. 基于Node.js镜像制作新镜像,使用国内源

Dockerfile:

FROM node:18.14.2-bullseye-slim

RUN sed -i 's#http://deb.debian.org#http://mirrors.cloud.tencent.com#g;s#http://security.debian.org#http://mirrors.cloud.tencent.com#g' /etc/apt/sources.list \
    && npm c set registry="https://registry.npmmirror.com" \
    && echo "puppeteer_download_host=https://registry.npmmirror.com/-/binary" >> ~/.npmrc

其中:http://mirrors.cloud.tencent.com 可以替换成任何一个国内debian镜像站域名

基于taobao.org的npm镜像域名已经失效,这里使用当前(2023-03-08为止)最新域名

npm v9已不再支持通过npm config set来设置自定义配置项,所以采用配置命令与手动追加配置文件相结合的形式

 

2. Puppeteer需要使用Chrome,但npm不会安装Chrome的依赖包,这里手动安装一下依赖包

Dockerfile:

RUN apt-get update \
    && apt-get install -y \
        ca-certificates \
        fonts-freefont-ttf \
        fonts-ipafont-gothic \
        fonts-kacst \
        fonts-liberation \
        fonts-thai-tlwg \
        fonts-wqy-zenhei \
        libappindicator3-1 \
        libasound2 \
        libatk-bridge2.0-0 \
        libatk1.0-0 \
        libc6 \
        libcairo2 \
        libcups2 \
        libdbus-1-3 \
        libexpat1 \
        libfontconfig1 \
        libgbm1 \
        libgcc1 \
        libglib2.0-0 \
        libgtk-3-0 \
        libnspr4 \
        libnss3 \
        libpango-1.0-0 \
        libpangocairo-1.0-0 \
        libstdc++6 \
        libx11-6 \
        libx11-xcb1 \
        libxcb1 \
        libxcomposite1 \
        libxcursor1 \
        libxdamage1 \
        libxext6 \
        libxfixes3 \
        libxi6 \
        libxrandr2 \
        libxrender1 \
        libxss1 \
        libxtst6 \
        lsb-release \
        wget \
        xdg-utils \
      --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

参考:官方文档-排障(英文)UNIX下无法启动无界面Chrome在Docker中运行Puppeteer 

官方给出的Docker方案和Dockerfile需要去谷歌服务器下载稳定版Chrome包,国内不方便使用,这里基于两部分内容进行了整合

 

3. Puppeteer默认需要沙盒模式,官方给出的方案是创建非root用户,由于项目其他需求,一部分组件必须使用root权限,这里在初始化Puppeteer时禁用沙盒

import puppeteer from "puppeteer";

async function usePuppeteer() {
  const browser = await puppeteer.launch({
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox"
    ],
  });
  try {

    // do something with browser...

  } finally {
    await browser.close();
  }
}

await usePuppeteer();

 

posted on 2022-10-18 17:35  不化的冰  阅读(1513)  评论(0编辑  收藏  举报