将docker环境变量传递到.net核心 [英] passing docker environment variables to .net core
问题描述
我已遵循以下文章和 github 上的代码不执行不编译,我认为教程已经过时了.( Configuration = builder.Build();
)引发错误.那么如何访问从docker传递的env?
I've followed this article and the code on the github doesn't compile, tutorial is outdated I think. (Configuration = builder.Build();
) throws error. So how can I access env passed from docker?
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!");
});
}
推荐答案
您可以在build参数中传递env变量.例如.
You can pass env variable in build argument. E.g.
-build-arg ASPNETCORE_ENVIRONMENT =开发
--build-arg ASPNETCORE_ENVIRONMENT=Development
使用下面的变量来设置值:
Use below variable to set value:
ASPNETCORE_ENVIRONMENT
ASPNETCORE_ENVIRONMENT
代码:
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
您可以在代码中使用上述变量作为环境名称.
You can use above variable in your code for environment name .
这篇关于将docker环境变量传递到.net核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!