【发布时间】:2021-07-15 03:00:26
【问题描述】:
我已经尝试了几乎所有可以在互联网上找到的解决方案,但没有任何效果。
在我的 .Net 5.0 应用程序中,我尝试在我的 appsettings.json 文件中使用环境变量和 Linux 上的“docker run”命令覆盖“IP”和“端口”的值。
这是我的 appsettings.json 文件:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Information",
"System": "Information",
"Microsoft": "Information"
}
},
"IPSettings": {
"IP": "192.168.230.131",
"Port": "10080"
}
}
这是我的 Dockerfile(我也尝试过不使用“ENV”行):
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
ENV IPSettings__IP='192.168.230.131'
ENV IPSettings__Port='10080'
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["HostServer.csproj", "."]
COPY ["QuicktronWrapper/QuicktronWrapper.csproj", "QuicktronWrapper/"]
RUN dotnet restore "./HostServer.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "HostServer.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "HostServer.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "HostServer.dll"]
我还在配置中添加了环境变量,如下所示:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
IConfigurationRoot configuration = builder.Build();
我当然可以从 appsettings.json 中获取这些值,因为我可以在 Windows 上运行应用程序而不会出现问题,方法是从 IIS 上的 Visual Studio 启动它。
现在,当我尝试在 Linux 上构建 docker 映像并运行它时,我在“docker run”命令中提供的值不会传递给我的应用程序。
以下是我使用的命令的变体,但似乎都没有工作:
docker run -it -p 4000:9999 --name HostServer hostserver \
-e "IPSettings:IP"="192.168.247.131" \
-e "IPSettings:Port"="10080"
docker run -e ASPNETCORE_IPSettings__IP="192.168.247.131" \
-e ASPNETCORE_IPSettings__Port="10080" \
-it -p 4000:9999 --name HostServer hostserver
docker run -e IPSettings__IP="192.168.247.131" \
-e IPSettings__Port="10080" \
-it -p 4000:9999 --name HostServer hostserver
这几天我一直在努力解决这个问题。我在这里错过了什么?
另外,如果我将 apsettings.json 中的值替换为我需要的值,然后使用以下命令:
docker run -it -p 4000:9999 --name HostServer hostserver
它在 Linux 上完美运行,这意味着问题肯定出在我传递环境变量的方式上。
【问题讨论】:
-
看起来不错。尝试从您的 dotnet 程序中打印出配置,如下所述:docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…
-
查看环境变量是否到达容器:
docker run --rm -it --entrypoint /bin/bash HostServer- 然后运行env -
@JevonKendon 谢谢,我这样做了,看起来环境变量没有到达容器。它显示 IPSettings__IP=192.168.230.131,但它应该显示 IPSettings__IP=192.168.247.131
-
docker run -it -e IPSettings__IP="192.168.247.131" --entrypoint /bin/bash --name HostServer hostserver应该可以工作;至少,我在这里的终端上有等价物。 Docker 可以特别关注参数顺序。试试这个特定的顺序。 -
@JevonKendon 您能否用您的解决方案回答问题,以便我将其标记为“已回答”并为您的答案投票?
标签: linux docker environment-variables .net-5