如果在 Docker 容器中运行 .NET 应用程序并想要使用开发代理,则需要执行几个步骤才能使其正常工作。
为 Docker 容器配置代理
由于 .NET 应用在 Docker 容器中运行,并且开发代理在主机上运行,因此需要将代理配置为指向计算机的 IP 地址(http://192.0.2.13
在以下示例中)。 .NET 使用 HTTPS_PROXY
环境变量为其 HTTP 客户端配置代理。 若要为 Docker 容器配置变量,请在启动容器时使用 --env, -e
此选项:
docker run --rm -it -v $(pwd):/usr/src/app -e HTTPS_PROXY=http://192.0.2.13:8000 mcr.microsoft.com/dotnet/sdk:8.0 bash
重要
在 macOS 上使用开发代理时,需要将其 0.0.0.0
附加到地址,以便从 Docker 容器访问它。 若要配置开发代理的 IP 地址,请使用以下命令启动它:
devproxy --ip-address 0.0.0.0
重要
在 Linux 上使用开发代理时,需要将其 0.0.0.0
附加到地址,以便从 Docker 容器访问它。 若要配置开发代理的 IP 地址,请使用以下命令启动它:
devproxy --ip-address 0.0.0.0
处理 SSL 证书
开发代理使用自己的 SSL 证书来检查从应用程序截获的 HTTPS 流量。 在计算机上安装开发代理时,它会生成自签名 SSL 证书,并将其添加到受信任的证书列表中。 但是,在 Docker 容器中运行应用程序时,容器无权访问计算机上安装的 SSL 证书。 将开发代理与 Docker 容器中运行的 .NET 应用程序配合使用时,有两种方法可以处理 SSL 证书。
在 Docker 容器中配置开发代理证书
若要允许开发代理检查 HTTPS 请求,可以将开发代理 SSL 证书配置为 Docker 容器中受信任的证书。
重要
由于 Docker 在关闭容器后不会保留对容器的更改,因此每次启动容器时都需要重复这些步骤。 若要避免这种情况,请创建包含以下步骤的自定义 Docker 映像。
首先,将开发代理证书导出到 PEM。
若要将开发代理证书导出到 Windows 上的 PEM,需要 openssl
。 此示例假定你 openssl
同时使用 git
了它,但你也可以单独安装它。
调整开发代理和 git 安装目录,并在 PowerShell 中运行以下脚本。
$proxyPath = "C:\apps\devproxy"
$gitPath = "C:\Program Files\Git"
# convert Dev Proxy root certificate to PEM
$executable = "${gitPath}\usr\bin\openssl.exe"
$arguments = 'pkcs12 -in "{0}\rootCert.pfx" -out "{0}\rootCert.crt" -nodes' -f $proxyPath
Start-Process -FilePath $executable -ArgumentList $arguments -NoNewWindow -Wait
# Read PEM contents
$content = Get-Content "$proxyPath\rootCert.crt"
# Find the indices of the begin and end certificate lines
$beginIndex = $content.IndexOf("-----BEGIN CERTIFICATE-----")
$endIndex = $content.IndexOf("-----END CERTIFICATE-----")
# If both lines are found
if ($beginIndex -ne -1 -and $endIndex -ne -1) {
# Trim the content to only include the certificate
$content = $content[$beginIndex..$endIndex]
}
# Write the updated content back to the file
$content | Out-File "$proxyPath\dev-proxy-ca.crt"
当系统提示输入密码时,按 Enter 而不键入任何内容。
# export Dev Proxy certificate
security find-certificate -c "Dev Proxy CA" -a -p > dev-proxy-ca.pem
# rename to .crt
mv dev-proxy-ca.pem dev-proxy-ca.crt
# export Dev Proxy certificate
openssl pkcs12 -in ~/.config/dev-proxy/rootCert.pfx -clcerts -nokeys -out dev-proxy-ca.crt -passin pass:""
# rename to .crt
mv dev-proxy-ca.pem dev-proxy-ca.crt
接下来,将证书复制到 Docker 容器。 复制证书的最简单方法是将其复制到装载到容器的项目文件夹。
然后,在 Docker 容器中信任证书。 如果使用 mcr.microsoft.com/dotnet/sdk
映像,可以使用以下命令:
# change to the directory where your application is located
cd /usr/app/src
# copy the certificate to the trusted certificates directory
cp dev-proxy-ca.crt /usr/local/share/ca-certificates
# update the trusted certificates
update-ca-certificates
在 .NET 应用程序中忽略 SSL 证书验证
将开发代理与 Docker 容器中运行的 .NET 应用程序配合使用时处理 SSL 证书的另一种方法是忽略应用程序中的 SSL 证书验证。 此方法要求修改应用程序代码。
在应用程序中,添加以下代码以忽略 SSL 证书验证:
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
注意
在将应用程序部署到生产环境之前,请务必删除此代码。