在咱们平常的开发过程当中,为了达到程序的灵活配置,咱们每每将一些可变参数保存到配置文件中,而后在集成打包部署的时候经过脚本指令来替换配置文件中的参数,针对Docker容器内的应用程序,Docker也为咱们提供了响应的替换方案,本篇文章主要为你们介绍一下如何灵活的替换Docker容器内.net core配置文件中的参数信息。ios
在进行.net core app的开发过程当中,.net core内置了一种新的参数信息读取方式,即读取.json文件,咱们能够将咱们程序中用到的可配置信息写入到json文件中,.net core内置的IConfiguration
接口能够很方便的读取json文件中的参数信息。docker
例如咱们在appsettings.json中添加一条数据信息,以下:"Service_Url": "234"
,完整的json文件内容为:json
{
"Logging":{
"LogLevel":{
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Service_Url": "234"
} 复制代码
咱们能够经过代码 this.Configuration.GetValue<string>("Service_Url");
获取到配置文件中的Service_Url值,完整的代码以下:bash
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中提供了两种方式为咱们动态的设置参数信息:cookie
在Dockerfile中进行参数的设置:app
在咱们定义Dockerfile的时候咱们能够将想要动态设置的参数在Dockerfile中进行定义,以下所示:post
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文件中进行参数的设置:ui
docker-compose.yml描述文件中为咱们提供了enviroment variable的定义方式,咱们能够将参数信息定义在这个属性下面,以下所示:this
dockernetcore:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
- Service_Url=123复制代码
咱们在environment中定义了变量Service_Url,并赋值为123,这样这个123也会替代咱们在json文件中定义的234。
以上即是两种替换变量值的方式,但愿经过该篇文章的介绍能够帮助你们更灵活的设置应用程序中用到的变量信息。