c# - 将 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!");
});
}
解决方案
在 .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
推荐阅读
- uima - UIMA Ruta - 比较注释的功能
- angular - 从另一个组件更新时ngclass不更新
- nativescript - 使用 Appium 的 Nativescript 测试不会在 iOS 上运行
- siddhi - 如何从过滤器中选择属性?
- excel - 如何将 Access 查询结果保存到 VBA 中的对象中?
- javascript - 如何使用用户定义的计算处理 Javascript 中的小数
- ionic-framework - 低于缺口的离子头
- python - numpy 线性代数求解器
- reactjs - 如何使用 React setState() 将状态设置为特定的常量值?
- python - 在 Excel 中运行 Python 脚本