.NET Core API Docker镜像运行报错:/app/chromedriver不存在
.NET Core API Docker镜像运行时chromedriver找不到的解决办法
问题原因
- 环境不兼容:你用的是Windows版本的
chromedriver.exe,但容器基于Linux镜像(mcr.microsoft.com/dotnet/aspnet:5.0默认是Linux环境),Linux下可执行文件不需要.exe后缀,且Windows格式的文件无法在Linux容器中运行。 - 文件未被正确复制到最终镜像:Dockerfile中
COPY ["Pand/chromedriver.exe", "."]的位置错误,该文件被复制到build阶段的/app目录,但dotnet publish只会打包项目输出文件到/app/publish,这个chromedriver并没有被包含进去,导致最终镜像的/app目录无此文件。 - 缺少Chrome浏览器:容器中未安装Chrome浏览器,即使driver存在,也无法启动浏览器实例。
解决方案
1. 准备Linux版chromedriver
下载与目标Chrome版本匹配的Linux版chromedriver(无需.exe后缀),放到项目的Pand目录下,本地执行chmod +x Pand/chromedriver赋予执行权限(也可在Dockerfile中设置)。
2. 修改Dockerfile
调整构建流程,确保chromedriver被复制到最终镜像,同时安装Chrome浏览器:
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443 # 安装Chrome浏览器(Linux环境) RUN apt-get update && apt-get install -y wget gnupg2 apt-transport-https RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list RUN apt-get update && apt-get install -y google-chrome-stable FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build WORKDIR /src COPY ["NuGet.Config", "."] COPY ["Pand/Pand.csproj", "Pand/"] COPY ["Pand.Application/Pand.Application.csproj", "Pand.Application/"] COPY ["Pand.Domain/Pand.Domain.csproj", "Pand.Domain/"] COPY ["Pand.Infrastructure/Pand.Infrastructure.csproj", "Pand.Infrastructure/"] RUN dotnet restore "Pand/Pand.csproj" # 复制整个项目文件 COPY . . WORKDIR "/src/Pand" RUN dotnet build "Pand.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "Pand.csproj" -c Release -o /app/publish # 将Linux版chromedriver复制到publish目录 COPY ["Pand/chromedriver", "/app/publish/"] # 赋予执行权限 RUN chmod +x /app/publish/chromedriver FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "Pand.dll"]
3. 调整代码中的chromedriver配置
在UpdatePriceScraper.cs中添加无头模式等容器运行必需的参数,并指定正确的driver路径:
var chromeOptions = new ChromeOptions(); // 容器中运行Chrome必须启用无头模式 chromeOptions.AddArgument("--headless"); // 禁用沙箱模式,避免权限问题 chromeOptions.AddArgument("--no-sandbox"); // 解决容器内存不足问题 chromeOptions.AddArgument("--disable-dev-shm-usage"); // 指定当前目录下的chromedriver var driver = new ChromeDriver(Directory.GetCurrentDirectory(), chromeOptions);
4. 重新构建并运行容器
执行以下命令重新构建镜像并运行:
docker build -t Pandgroup/backend -f Pand/Dockerfile . docker run -p 8080:80 Pandgroup/backend
内容的提问来源于stack exchange,提问作者Sasan
相关产品推荐
相关产品推荐

