passing docker environment variables to .net core

让人想犯罪 __ 提交于 2021-02-18 07:34:29

问题


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

回答1:


You can pass env variable in build argument. E.g.

--build-arg ASPNETCORE_ENVIRONMENT=Development

Use below variable to set value:

ASPNETCORE_ENVIRONMENT

Code:

var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

You can use above variable in your code for environment name .




回答2:


The standard approach to access environment variables in a .NET Core application is to use the static method

public static string GetEnvironmentVariable (string variable);

So in your case irrespective of what you pass either in the docker run command or through the launch settings file just use this method . As an example for getting the Database password use this

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

Additionally be sure to define the environment variables part of the dockerfile by adding the line

ENV DATABASE_PASSWORD some_default_value_or_can_be_empty


来源:https://stackoverflow.com/questions/58318960/passing-docker-environment-variables-to-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!