在 Alpine Linux 中运行 Chrome headless 需要哪些依赖库?
解读
国内 CI/CD 环境(如阿里云效、腾讯云 Coding、华为云 DevCloud)普遍采用 Alpine Linux 作为基础镜像,因其体积小于 5 MB,可显著缩短构建时间。然而 Alpine 使用 musl libc 而非 glibc,而 Google 官方发布的 Chrome 二进制依赖 glibc 及一系列 Debian/Ubuntu 系动态库。若缺失这些库,Selenium 启动 Chrome headless 时会直接报 “chrome: not found” 或 “error while loading shared libraries” 等错误,导致流水线失败。面试官通过此题考察候选人是否具备 “最小容器+最大兼容性” 的实战排障能力,以及是否熟悉国内镜像源加速方案。
知识点
- Alpine 软件管理机制:apk 包管理器、edge/community 仓库、国内清华/中科大镜像源
- Chrome 运行时依赖的 glibc 兼容层(alpine 自身 musl 不满足)
- 共享库定位命令:ldd chrome | grep “not found”
- Selenium 启动参数:--no-sandbox、--disable-dev-shm-usage、--disable-gpu、--headless=new
- 国内合规下载渠道:npm.taobao.org 的 chromedriver 镜像、腾讯软件源、华为开源镜像站
- 镜像体积优化技巧:多阶段构建、删除缓存、合并 RUN 指令、使用 glibc-i18n 最小语言包
- 安全加固:非 root 用户(adduser -D -s /bin/bash selenium)+ 沙箱权衡(CI 环境通常关闭 sandbox)
答案
在 Alpine Linux 中运行 Chrome headless 必须手动补齐 glibc 兼容层 及 Chrome 所需的全部动态库,步骤如下:
-
添加国内源加速
将/etc/apk/repositories替换为清华源:https://mirrors.tuna.tsinghua.edu.cn/alpine/edge/main与edge/community。 -
安装基础工具
apk add --no-cache bash wget unzip -
安装 glibc 兼容层(使用 sgerrand/alpine-pkg-glibc 社区包,国内可缓存到自建 Nexus)
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.35-r1/glibc-2.35-r1.apk apk add --no-cache --force-overwrite glibc-2.35-r1.apk -
安装 Chrome 依赖的 Debian 系动态库(经 ldd 验证的最小集合)
apk add --no-cache \ nss \ freetype \ freetype-dev \ harfbuzz \ ca-certificates \ ttf-freefont \ fontconfig \ dbus \ libx11 \ libxcomposite \ libxdamage \ libxrandr \ libxext \ libxrender \ mesa-gl \ alsa-lib \ libxcb \ libxshmfence \ libxfixes \ libxcursor \ libxi \ libxtst \ libatk-bridge-2.0 \ libgtk-3 \ gdk-pixbuf -
下载并解压 官方 Chrome 二进制(国内建议走华为镜像站缓存)
wget -q -O chrome.deb https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_125.0.6422.141-1_amd64.deb dpkg-deb -x chrome.deb /tmp/chrome cp -r /tmp/chrome/opt/google/chrome /opt/ ln -s /opt/chrome/chrome /usr/local/bin/chrome -
验证依赖完整性
ldd /opt/chrome/chrome | grep "not found"若输出为空,则依赖全部满足。 -
Selenium 代码示例(Python)
from selenium import webdriver options = webdriver.ChromeOptions() options.binary_location = "/usr/local/bin/chrome" options.add_argument("--headless=new") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(options=options) driver.get("https://www.example.com") print(driver.title) driver.quit()
至此,Alpine 容器可在 无桌面、无 root、无 GPU 场景下稳定运行 Chrome headless,满足国内 Jenkins/K8s 流水线要求。
拓展思考
- 若公司要求 “零合规风险”,不允许使用社区 glibc 包,可考虑改用 Ubuntu 22.04 minimal 作为基础镜像,体积约 80 MB,仍远小于完整 Ubuntu,且官方 glibc 无需额外兼容。
- 当并发量高时,
/dev/shm默认 64 MB 易导致 Chrome 崩溃,除--disable-dev-shm-usage外,还可在 K8s YAML 中增加emptyDir.medium: Memory并挂载到/dev/shm,大小按需设置。 - 国内网络抖动场景,建议把 Chrome 与 Chromedriver 一并打入 企业私有镜像仓库,并通过 SHA256 校验 保证完整性,避免构建时因下载失败导致流水线随机失败。