在我们日常的开发过程中,为了达到程序的灵活配置,我们往往将一些可变参数保存到配置文件中,然后在集成打包部署的时候通过脚本指令来替换配置文件中的参数,针对Docker容器内的应用程序,Docker也为我们提供了响应的替换方案,本篇文章主要为大家介绍一下如何灵活的替换Docker容器内.net core配置文件中的参数信息。
在进行.net core app的开发过程中,.net core内置了一种新的参数信息读取方式,即读取.json文件,我们可以将我们程序中用到的可配置信息写入到json文件中,.net core内置的IConfiguration
接口可以很方便的读取json文件中的参数信息。
例如我们在appsettings.json中添加一条数据信息,如下:"Service_Url": "234"
,完整的json文件内容为:
{
"Logging":{
"LogLevel":{
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Service_Url": "234"
}
我们可以通过代码 this.Configuration.GetValue<string>("Service_Url");
获取到配置文件中的Service_Url值,完整的代码如下:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
string Service_Url = this.Configuration.GetValue<string>("Service_Url");
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//Init Logger
}
}
因为很多时候我们开发环境,测试环境还有生成环境的某些参数配置是不一样的,因此我们需要将一些参数进行动态的设置,在docker中提供了两种方式为我们动态的设置参数信息:
在Dockerfile中进行参数的设置:
在我们定义Dockerfile的时候我们可以将想要动态设置的参数在Dockerfile中进行定义,如下所示:
FROM microsoft/dotnet:2.2-aspnetcore-runtime-nanoserver-1803 AS base
WORKDIR /app
ENV Service_Url 456
EXPOSE 80
EXPOSE 443
上面的语法中,我们在Dockerfile中添加名为Service_Url的变量,并将其值设定为456,这样这个456就会覆盖之前我们在json文件中定义的234了。
在docker-compose.yml文件中进行参数的设置:
docker-compose.yml描述文件中为我们提供了enviroment variable的定义方式,我们可以将参数信息定义在这个属性下面,如下所示:
dockernetcore:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
- Service_Url=123
我们在environment中定义了变量Service_Url,并赋值为123,这样这个123也会替代我们在json文件中定义的234。
以上便是两种替换变量值的方式,希望通过该篇文章的介绍可以帮助大家更灵活的设置应用程序中用到的变量信息。