M1 Mac环境下Docker中安装sharp依赖报错的解决方案问询
报错内容:
error /usr/src/app/node_modules/sharp: Command failed. Exit code: 1 Command: (node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy) Arguments: Directory: /usr/src/app/node_modules/sharp Output: sharp: Installation error: Use with glibc 2.24 requires manual installation of libvips >= 8.11.3 sharp: Please see https://sharp.pixelplumbing.com/install for required dependencies
首先明确:Mac本机通过brew安装的libvips无法被Docker容器识别,Docker容器是独立隔离的运行环境,和宿主机的软件包、文件系统完全无关,因此本机安装的依赖对容器内构建没有作用。
以下是可行的解决方案:
方案1:容器内预装符合要求的libvips(最稳妥)
你使用的sharp 0.29.0要求libvips >=8.11.3,优先选择适配arm64(M1架构)的Debian 11+/Ubuntu 22.04+的Node.js基础镜像,比如node:16-bullseye(可根据你的Node版本调整对应标签),然后在Dockerfile中执行yarn install前添加以下命令:
# 安装系统级libvips依赖 RUN apt-get update && apt-get install -y --no-install-recommends \ libvips-dev \ && rm -rf /var/lib/apt/lists/* # 配置sharp强制使用系统安装的libvips ENV SHARP_FORCE_GLOBAL_LIBVIPS=1 # 执行依赖安装 RUN yarn install
方案2:直接下载对应架构的sharp预编译二进制
无需安装全局libvips,通过环境变量配置sharp拉取对应容器架构的预编译包即可,Dockerfile配置示例:
# 配置忽略全局libvips,拉取对应架构的预编译二进制 ENV SHARP_IGNORE_GLOBAL_LIBVIPS=1 # 可配置国内镜像源提升下载速度 ENV npm_config_sharp_binary_host=https://npmmirror.com/mirrors/sharp ENV npm_config_sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips RUN yarn install
方案3:导入本地构建的libvips到容器
如果需要使用自定义编译的libvips,首先要确保本地编译的libvips架构和容器运行架构一致(M1设备上需要编译arm64版本的libvips,容器也需要使用arm64架构的基础镜像),然后在Dockerfile中添加以下配置:
# 把本地编译好的libvips目录复制到容器的系统路径 COPY ./本地编译后的libvips目录/ /usr/local/ # 刷新动态链接库缓存 RUN ldconfig # 配置sharp使用全局libvips ENV SHARP_FORCE_GLOBAL_LIBVIPS=1 RUN yarn install
注意:如果使用alpine系的基础镜像,默认使用musl libc而不是glibc,会额外增加兼容成本,非必要不推荐使用。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

