Jenkins构建失败:NuGet无法连接远程服务器
解决NuGet通过Jenkins代理访问失败的问题
从你描述的构建报错和配置来看,核心问题出在NuGet代理配置与Jenkins代理环境的匹配上,我整理了几个针对性的解决方案:
1. 修正NuGet代理协议配置
你的NuGet配置里把http_proxy设为https://myhostname:80,但实际上NuGet的http_proxy配置项无论目标源是HTTP还是HTTPS,都应该用HTTP协议指向代理地址(除非你的代理本身是HTTPS类型,而大部分内部/企业代理都是HTTP)。
修改你的NuGet.config:
<?xml version="1.0" encoding="utf-8"?> <configuration> <config> <!-- 将https协议改为http --> <add key="http_proxy" value="http://myhostname:80" /> <!-- 如果代理需要身份验证,补充以下两项配置 --> <!-- <add key="http_proxy.user" value="你的代理用户名" /> --> <!-- <add key="http_proxy.password" value="你的代理密码" /> --> </config> <packageSources> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" /> </packageSources> </configuration>
2. 让NuGet继承Jenkins的代理环境变量
Jenkins本身配置了代理,但NuGet可能没自动读取到对应的环境变量。你可以在MSBuild构建步骤前,手动添加环境变量配置:
- 如果是Windows环境,添加「Execute Windows batch command」步骤,输入:
set HTTP_PROXY=http://myhostname:80 set HTTPS_PROXY=http://myhostname:80
- 如果是Linux/macOS环境,添加「Execute shell」步骤,输入:
export HTTP_PROXY=http://myhostname:80 export HTTPS_PROXY=http://myhostname:80
这样NuGet执行还原操作时会优先读取这些环境变量,和Jenkins的代理配置保持一致。
3. 验证代理是否允许访问NuGet源
有时候代理服务器会拦截外部源的请求,你可以在Jenkins服务器上手动测试连通性:
- Linux/macOS用curl测试:
curl -x http://myhostname:80 https://api.nuget.org/v3/index.json
- Windows用PowerShell测试:
Invoke-WebRequest -Uri https://api.nuget.org/v3/index.json -Proxy http://myhostname:80
如果测试失败,说明代理限制了NuGet源的访问,需要联系运维团队开放权限。
4. 升级NuGet版本排除兼容性问题
部分旧版本的NuGet对代理的支持存在bug,建议升级到最新稳定版:
- 在Jenkins「全局工具配置」中找到NuGet,设置安装最新版本;
- 或者在构建步骤中手动升级并执行还原:
nuget update -self nuget restore YourProject.sln
内容的提问来源于stack exchange,提问作者Kartik Makkar




