Docker部署Puppeteer(NestJs)PDF生成应用时浏览器未找到求助
尝试用Docker部署基于NestJS、依赖Puppeteer生成PDF的应用时,反复遇到浏览器未找到的错误:
Error: Browser was not found at the configured executablePath (/usr/bin/google-chrome-stable)
throw new Error(Browser was not found at the configured executablePath (${launchArgs.executablePath}));
已尝试在容器内安装Chrome、使用官方Puppeteer镜像、改用puppeteer-core,但错误始终存在,即使修改executablePath,报错仍指向/usr/bin/google-chrome-stable。
当前使用的Dockerfile:
# Base image FROM ghcr.io/puppeteer/puppeteer:23.3.0 # Create app directory WORKDIR /app # A wildcard is used to ensure both package.json AND package-lock.json are copied COPY package*.json ./ # Install app dependencies RUN npm install # Bundle app source COPY . . EXPOSE 4001 # Start the server using the production build CMD ["npm", "run", "start:prod"]
浏览器服务单例代码:
async onModuleInit() { const browserConfigs = { headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], browser: 'chrome', } as puppeteer.PuppeteerLaunchOptions; if (this.profile !== 'development') { browserConfigs.executablePath = '/usr/bin/google-chrome-stable)'; } this.browser = await puppeteer.launch(browserConfigs); this.page = await this.browser.newPage(); this.page.setDefaultTimeout(0); this.page.setDefaultNavigationTimeout(0); }
Puppeteer版本:23.3.0
1. 修正路径拼写错误
代码中executablePath的值末尾多了一个多余的右括号,直接移除即可:
if (this.profile !== 'development') { browserConfigs.executablePath = '/usr/bin/google-chrome-stable'; }
2. 确认官方镜像内Chrome的实际路径
ghcr.io/puppeteer/puppeteer:23.3.0镜像中,Chrome的实际路径是/usr/bin/google-chrome,而非/usr/bin/google-chrome-stable。可进入容器验证:
docker exec -it <容器ID> which google-chrome
修改配置路径为正确值:
browserConfigs.executablePath = '/usr/bin/google-chrome';
3. 无需手动指定路径(推荐)
官方Puppeteer镜像已配置好环境变量,Puppeteer可自动识别浏览器路径,直接移除生产环境下的路径指定代码:
async onModuleInit() { const browserConfigs = { headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], browser: 'chrome', } as puppeteer.PuppeteerLaunchOptions; this.browser = await puppeteer.launch(browserConfigs); this.page = await this.browser.newPage(); this.page.setDefaultTimeout(0); this.page.setDefaultNavigationTimeout(0); }
4. 确保容器运行权限
官方镜像默认使用puppeteer用户运行,若出现权限问题,可在Dockerfile中调整:
USER root # 或确保puppeteer用户拥有访问浏览器的权限
5. 改用puppeteer-core优化
若使用puppeteer-core,需在package.json中替换依赖:
"dependencies": { "puppeteer-core": "23.3.0" }
无需额外安装Chrome,直接利用镜像自带的浏览器即可。
内容的提问来源于stack exchange,提问作者Felipe Oliveira Sousa

