首页 > 解决方案 > 将 docker 环境变量传递给 .net 核心

问题描述

我已经关注了这篇文章,但github上的代码无法编译,我认为教程已经过时了。( Configuration = builder.Build();) 抛出错误。那么如何访问从 docker 传递的 env 呢?


码头工人撰写

  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

启动.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!");
    });
}

标签: c#dockerasp.net-core

解决方案


在 .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

推荐阅读