C# 将docker环境变量传递给.net core
我已经遵循了这一点,并且上的代码没有编译,我认为教程已经过时了。(C# 将docker环境变量传递给.net core,c#,docker,asp.net-core,C#,Docker,Asp.net Core,我已经遵循了这一点,并且上的代码没有编译,我认为教程已经过时了。(Configuration=builder.Build();)引发错误。那么如何访问docker传递的env docker compose myproj: image: mcr.microsoft.com/dotnet/core/sdk:2.2 restart: on-failure working_dir: /MyProj command: bash -c "dotnet build MyP
Configuration=builder.Build();
)引发错误。那么如何访问docker传递的env
docker compose
myproj:
image: mcr.microsoft.com/dotnet/core/sdk:2.2
restart: on-failure
working_dir: /MyProj
command: bash -c "dotnet build MyProj.csproj && dotnet bin/Debug/netcoreapp2.2/MyProj.dll"
ports:
- 5001:5001
- 5000:5000
volumes:
- "./MyProj:/MyProj"
environment:
DATABASE_HOST: database
DATABASE_PASSWORD: Password
Startup.cs
public Service()
{
Environment.GetEnvironmentVariable("DATABASE_PASSWORD"); // null
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
context.Response.WriteAsync("Hello World!");
});
}
可以在生成参数中传递env变量。 例如 使用以下变量设置值:
ASPNETCORE\u环境
代码:
您可以在代码中使用上述变量作为环境名称。在.NET核心应用程序中访问环境变量的标准方法是使用静态方法
public static string GetEnvironmentVariable (string variable);
因此,在您的情况下,无论您在docker run命令中或通过launch settings文件传递什么,都只需使用此方法。作为获取数据库密码的示例,请使用
string dbPassword = Environment.GetEnvironmentVariable("DATABASE_PASSWORD");
另外,请确保通过添加行来定义dockerfile的环境变量部分
ENV DATABASE_PASSWORD some_default_value_or_can_be_empty
这应该是公认的答案。使用.NET Core 2.1及更高版本中的
环境变量配置提供程序
将环境变量注入到IConfiguration
,也毫无价值。更多信息:这不起作用的最可能原因是什么?当获取环境变量时,它是空的。它是在dockerfile中定义的吗…?对我来说也是一样,我尝试使用“docker run-e”和“docker run--env file”传递环境变量,并在代码中获取null。我已尝试打印我的.net core 3.1应用程序在容器中可以访问的所有环境变量,我只能看到“ASPNETCORE\u URL、在容器中运行的DOTNET\u、路径、主机名、主页和路径”,但看不到我的自定义环境变量。。。
string dbPassword = Environment.GetEnvironmentVariable("DATABASE_PASSWORD");
ENV DATABASE_PASSWORD some_default_value_or_can_be_empty