Skip to main content
 首页 » 编程设计

c#之将 docker 环境变量传递给 .net core

2024年01月29日35小虾米

我关注了这个 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!"); 
    }); 
} 

请您参考如下方法:

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