You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker build中--build-arg无法传递NuGet私有源凭证问题求助

问题解决:Docker构建时无法通过--build-arg传递NuGet仓库凭证

问题原因

你在Dockerfile中直接使用$USERNAME和$GITHUB_TOKEN变量,但没有在对应构建阶段声明ARG指令,导致Docker构建时不会将命令行传入的--build-arg参数注入到当前构建环节的环境中,自然无法读取到凭证值。而硬编码时变量被直接替换,所以能正常工作。

修复方案

在build阶段的开头添加ARG声明,明确告诉Docker要接收这两个构建参数,之后再使用变量即可。

修改后的Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
# 声明要接收的构建参数,作用域仅限当前build阶段
ARG USERNAME
ARG GITHUB_TOKEN
WORKDIR /app
COPY . .
RUN dotnet nuget add source --username $USERNAME --store-password-in-clear-text --password $GITHUB_TOKEN --name notification "https://nuget.github.xxx.com/notification/index.json"
RUN dotnet restore
RUN dotnet publish -c Release -o /app/publish

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish /app
ENTRYPOINT ["dotnet", "notification-api.dll"]
EXPOSE 80

额外优化建议

  • 可以将dotnet nuget add source和dotnet restore合并为一步,减少镜像层:
    RUN dotnet nuget add source --username $USERNAME --store-password-in-clear-text --password $GITHUB_TOKEN --name notification "https://nuget.github.xxx.com/notification/index.json" && dotnet restore
    
  • 由于采用多阶段构建,runtime阶段不会包含build阶段的NuGet源配置和凭证痕迹,无需额外清理即可保证镜像安全性。

内容的提问来源于stack exchange,提问作者Çağrı BIYIK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:43:53