将docker环境变量传递到.net核心

时间:2019-10-10 08:51:20

标签: c# docker asp.net-core

我已遵循此article,但github上的代码未编译,我认为教程已过时。 (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!");
    });
}

2 个答案:

答案 0 :(得分:3)

您可以在build参数中传递env变量。 例如。

-build-arg ASPNETCORE_ENVIRONMENT =开发

使用下面的变量来设置值:

ASPNETCORE_ENVIRONMENT

代码:

var environmentName = Environment.GetEnvironmentVariable(“ ASPNETCORE_ENVIRONMENT”);

您可以在代码中使用以上变量作为环境名称。

答案 1 :(得分:2)

在.NET Core应用程序中访问环境变量的标准方法是使用静态方法

public static string GetEnvironmentVariable (string variable);

因此,对于您而言,无论您在docker run命令中传递的内容还是在启动设置文件中传递的内容,都只需使用此方法。作为获取数据库密码的示例,请使用

string dbPassword = Environment.GetEnvironmentVariable("DATABASE_PASSWORD");

另外,请确保通过添加以下行来定义dockerfile的环境变量部分

ENV DATABASE_PASSWORD some_default_value_or_can_be_empty