解決 Docker Alpine 與 Puppeteer 的 Error: Failed to launch the browser process! 錯誤
前後端工程師,善用 JavaScript、HTML 5、CSS 3 和 Golang 與 PHP、Node.js 、C#。目前正為台灣的社群網站進行趕工,然而這東西卻趕了很久。

很奇怪的不知道為什麼 Docker Alpine 執行 Puppeteer(Node.js 的一套操控 Chrome 函式庫)會顯示下列錯誤。

Error: Failed to launch the browser process! spawn /root/my-project/node_modules/puppeteer/.local-chromium/linux-818858/chrome-linux/chrome ENOENT

這很明顯是在說當初 npm install puppeteer 的時候 Chromium 沒有正確地解壓縮或是安裝,但是檢查目錄之後發現 Chrome 又確實在那裡。為了真正解決這個問題,最後我的作法是查看 Puppeteer 官方給的疑難排解手冊

在 Alpine 裡安裝一個原生的 Chromium,並且透過環境變數指定告訴 Puppeteer 不要使用 node_modules 裡面的 chromium 執行,而是系統的瀏覽器。

$ apk add --no-cache \
      chromium \
      nss \
      freetype \
      freetype-dev \
      harfbuzz \
      ca-certificates \
      ttf-freefont \
      nodejs \
      yarn
$ PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
    PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser

執行兩行指令之後,基本上重新執行 Node.js 專案就沒有問題了。但如果一樣找不到 Chrome 瀏覽器,那就是環境變數可能要到 /etc/profile 進行變更,然後重新啟動整個環境。