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



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


码头工人撰写

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

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

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

--build-arg ASPNETCORE_ENVIRONMENT=Development

使用以下变量设置值:

ASPNETCORE_ENVIRONMENT

法典:

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

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

您可以使用IConfiguration读取值,默认情况下,这些值都为您完成。如果您在Program.cs中为主机配置了默认值,则它将按以下顺序加载配置

  1. appset.json
  2. 应用设置..杰森
  3. 秘密.json
  4. 环境变量
  5. CLI 参数

例如,你可以有一个类

public class DatabaseSettings
{
public string Host { get; set; }
public string Password { get; set; }
}

然后在Startup.cs中读取值并将它们绑定到DatabaseSettings对象。

var credentials = Configuration.GetSection("Database").Get<DatabaseSettings>();

注意:您的环境变量必须具有双下划线才能在键和值部分之间分隔。

例如,如果要从appsettings.jsonappsettings.Development.json文件传递此对象,则此分层JSON对象

"Database": {
"Host": "address",
"Password": "password" 
}

像这样扁平化时也可以表示

"Database:Host":"address",
"Database:Password":"Password"

或者当作为环境变量传递时,可以作为

Database__Host=address
Database__Password=password

请记住,您需要双下划线。

如果有人使用 Docker-compose.yml 环境变量而不是 appsettings.json,请将以下代码添加到 IHostBuilder

字符串 someVariable = Environment.GetEnvironmentVariable("Environment Variable Name"(;

最新更新