.NET Core 使用 K8S ConfigMap的正确姿势
背景
ASP.NET Core默认的配置文件定义在appsetings.json
和appsettings.{Environment}.json
文件中。
这里面有一个问题就是,在使用容器部署时,每次修改配置文件都需要重新构建镜像。当然你也可能会说,我的配置文件很稳定不需要修改,但你又如何确保配置文件中一些机密配置的安全问题呢?比如暴露了你的远程数据库的连接信息,哪天被员工不小心删库跑路了呢?
那接下来就来讲解下如何在.NET Core 中正确使用ConfigMap。
ConfigMap/Secret
K8S中引入了ConfigMap/Secret来存储配置数据,分别用于存储非敏感信息和敏感信息。其目的在于将应用和配置解耦,以确保容器化应用程序的可移植性。
创建 ConfigMap
玩耍K8S,请先自行准备环境,Win10用户可以参考我的上篇文章ASP.NET Core 借助 K8S 玩转容器编排来准备环境。
ConfigMap的创建很简单,一句命令就可以直接将appsettings.json
文件转换为ConfigMap。
PS:使用K8S一定要善用帮助命令,比如执行kubectl create configmap -h
,你就可以了解到多种创建ConfigMap的方式。
> kubectl create configmap -h
Create a configmap based on a file, directory, or specified literal value.
A single configmap may package one or more key/value pairs.
When creating a configmap based on a file, the key will default to the basename of the file, and the value will default
to the file content. If the basename is an invalid key, you may specify an alternate key.
When creating a configmap based on a directory, each file whose basename is a valid key in the directory will be
packaged into the configmap. Any directory entries except regular files are ignored (e.g. subdirectories, symlinks,
devices, pipes, etc).
Aliases:
configmap, cm
Examples:
# Create a new configmap named my-config based on folder bar
kubectl create configmap my-config --from-file=path/to/bar
# Create a new configmap named my-config with specified keys instead of file basenames on disk
kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt
# Create a new configmap named my-config with key1=config1 and key2=config2
kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2
# Create a new configmap named my-config from the key=value pairs in the file
kubectl create configmap my-config --from-file=path/to/bar
# Create a new configmap named my-config from an env file
kubectl create configmap my-config --from-env-file=path/to/bar.env
其中我们可以看到可以通过指定--from-file
来从指定文件创建。
kubectl create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-file=key2=/path/to/bar/file2.txt
Let's have a try!
1. 先行创建示例项目:dotnet new mvc -n K8S.NETCore.ConfigMap
2. 默认包含两个配置文件appsettings.json
和appsettings.Development.json
3. 先来尝试将appsettings.json
转换为ConfigMap:
> cd K8S.NETCore.ConfigMap
# 创建一个namespace,此步可选
> kubectl create namespace demo
namespace "demo" created
# -n变量指定configmap创建到哪个namespace下
> kubectl create configmap appsettings --from-file=appsettings.json=./appsettings.json -n demo
configmap "appsettings" created
# 查看刚刚创建的configmap,-o指定输出的格式
> kubectl get configmap appsettings -n demo -o yaml
apiVersion: v1
data:
appsettings.json: "{\r\n \"Logging\": {\r\n \"LogLevel\": {\r\n \"Default\":
\"Warning\"\r\n }\r\n },\r\n \"AllowedHosts\": \"*\"\r\n}\r\n"
kind: ConfigMap
metadata:
creationTimestamp: null
name: appsettings
namespace: demo
从上面的输出结果来看,其中包含了\r\n
换行符,显然不是我们想要的结果。猜测是因为Windows和Linux系统换行符的差异导致的。先来插播下换行符的知识:
CR:Carriage Return,对应ASCII中转义字符\r,表示回车
LF:Linefeed,对应ASCII中转义字符\n,表示换行
CRLF:Carriage Return & Linefeed,\r\n,表示回车并换行
众所周知,Windows操作系统采用两个字符来进行换行,即CRLF;Unix/Linux/Mac OS X操作系统采用单个字符LF来进行换行;
所以解决方式就很简单,将换行符切换为Linux系统的\n
即可。操作方式很简单:
对于VS Code 只需要按图下所示操作即可,点击右下角的CRLF
,选择LF
即可。
对于VS,如果VS打开json文件有下面的提示,直接切换就好。没有,可以安装Line Endings Unifier扩展来统一处理。
# 先删除之前创建的configmap
> kubectl delete configmap appsettings -n demo
> kubectl create configmap appsettings --from-file=appsettings.json=./appsettings.json -n demo
configmap "appsettings" created
> kubectl get configmap appsettings -n demo -o yaml
apiVersion: v1
data:
appsettings.json: |
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
kind: ConfigMap
metadata:
creationTimestamp: null
name: appsettings
namespace: demo
现在ConfigMap的格式正常了。下面我们尝试把appsettings.Development.json
也合并到一个ConfigMap中。
> kubectl delete configmap appsettings -n demo
> kubectl create configmap appsettings --from-file=appsettings.json=./appsettings.json --from-file=appsettings.Development.json=./appsettings.Development.json -n demo
configmap "appsettings" created
> kubectl get configmap appsettings -n demo -o yaml
apiVersion: v1
data:
appsettings.Development.json: |
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
appsettings.json: |
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
kind: ConfigMap
metadata:
creationTimestamp: null
name: appsettings
namespace: demo
PS:
- 如果你的配置文件包含多余的空格,则生成的ConfigMap可能就会包含
\n
字符,就像这样:
appsettings.Development.json: "{\n \"Logging\": {\n \"LogLevel\": {\n \"Default\": \"Debug\",\n \"System\": \"Information\",\n \"Microsoft\": \"Information\"\n \ }\n }\n} \n"
。解决办法就是保存文件时记得格式化文件就好了,或者手动删除多余空格。- 创建ConfigMap的时候可以指定
--dry-run
参数进行试运行,避免直接创建到服务器。- 从文件创建ConfigMap时,可以不指定Key,默认会以文件名为Key。
kubectl create configmap appsettings --from-file=./appsettings.json --from-file=./appsettings.Development.json -n demo --dry-run -o yaml
至此,完成了appsetting到configmap的切换。
应用 ConfigMap
ConfigMap的应用很简单,只需要将configmap挂载到容器内的独立目录即可。
先来看一下借助VS帮生成的Dockerfile。
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["K8S.NETCore.ConfigMap.csproj", ""]
RUN dotnet restore "./K8S.NETCore.ConfigMap.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "K8S.NETCore.ConfigMap.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "K8S.NETCore.ConfigMap.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "K8S.NETCore.ConfigMap.dll"]
可以看出文件中定义的WORKDIR /app
指定的工作目录为/app
,所以需要把ConfigMap挂载到/app
目录下。先执行docker build -t k8s.netcore.configmap:dev .
构建镜像。
我们来新建一个configmap-deploy.yaml
文件配置如下:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: k8s-configmap-demo
spec:
selector:
matchLabels:
app: k8s-configmap-demo
template:
metadata:
labels:
app: k8s-configmap-demo
spec:
containers:
- name: k8s-configmap-demo
image: k8s.netcore.configmap:dev
imagePullPolicy: IfNotPresent
resources:
limits:
memory: "128Mi"
cpu: "500m"
ports:
- containerPort: 80
volumeMounts:
- mountPath: /app/appsettings.json
name: test
readOnly: true
subPath: appsettings.json
- mountPath: /app/appsettings.Development.json
name: test
readOnly: true
subPath: appsettings.Development.json
volumes:
- configMap:
defaultMode: 420
name: appsettings
name: test
这里有必要解释两个参数:
- volumes:-configMap:指定引用哪个ConfigMap
- volumeMounts:用来指定将ConfigMap中的配置挂载到容器的哪个路径
- subPath:用来指定引用ConfigMap的哪个配置节点。
创建Deployment之前先修改下ConfigMap的配置,以方便确认最终成功从ConfigMap挂载配置。将Logging:LogLevel:Default:
节点的默认值改为Error。
> kubectl edit configmap appsettings -n demo
configmap/appsettings edited
> kubectl get cm appsettings -n demo -o yaml
apiVersion: v1
data:
appsettings.Development.json: |-
{
"Logging": {
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
}
}
}
appsettings.json: |
{
"Logging": {
"LogLevel": {
"Default": "Error"
}
},
"AllowedHosts": "*"
}
kind: ConfigMap
metadata:
creationTimestamp: "2019-09-02T22:50:14Z"
name: appsettings
namespace: demo
resourceVersion: "445219"
selfLink: /api/v1/namespaces/demo/configmaps/appsettings
uid: 07048d5a-cdd4-11e9-ad6d-00155d3a3103
修改完毕后,执行后续命令来创建Deployment,并验证。
# 创建deployment
> kubectl apply -f .\k8s-deploy.yaml -n demo
deployment.extensions/k8s-configmap-demo created
# 获取创建的pod
> kubectl get pods -n demo
NAME READY STATUS RESTARTS AGE
k8s-configmap-demo-7cfbdfff67-xdrcx 1/1 Running 0 12s
# 进入pod内部
> kubectl exec -it k8s-configmap-demo-7cfbdfff67-xdrcx /bin/bash -n demo
root@k8s-configmap-demo-7cfbdfff67-xdrcx:/app# cat appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Error"
}
},
"AllowedHosts": "*"
}
root@k8s-configmap-demo-7cfbdfff67-xdrcx:/app# cat appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
}
}
}
从以上输出可以看出,默认的配置项已被ConfigMap的配置覆盖。
热更新
以Volume方式挂载的ConfigMap支持热更新(大概需要10s左右)。但一种情况例外,就是指定subPath的情况下,更新ConfigMap,容器中挂载的ConfigMap是不会自动更新的。
A container using a ConfigMap as a subPath volume will not receive ConfigMap updates.
对于这种情况,也很好处理,将ConfigMap挂载到/app
目录下一个单独目录就好,比如挂载到/app/config
目录,然后修改配置文件的加载路径即可。
hostBuilder.ConfigureAppConfiguration((context, builder) =>
{
builder.SetBasePath(Path.Join(AppContext.BaseDirectory, "config"))
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true);
});
最后
本文就.NET Core如何应用ConfigMap进行了详细的介绍。其中最关键在于appsettings.json到ConfigMap的转换,以及挂载目录的指定。希望对你有所帮助。
而至于Secret的应用,原理相通了,关键在于Secret的生成,这里就交给你自己探索了。
.NET Core 使用 K8S ConfigMap的正确姿势的更多相关文章
- ASP.NET Core on K8S深入学习(9)Secret & Configmap
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 一.Secret 1.1 关于Secret 在应用启动过程中需要一些敏感信息, ...
- ASP.NET Core 2.0 中读取 Request.Body 的正确姿势
原文:ASP.NET Core 中读取 Request.Body 的正确姿势 ASP.NET Core 中的 Request.Body 虽然是一个 Stream ,但它是一个与众不同的 Stream ...
- .NET Core技术研究-HttpContext访问的正确姿势
将ASP.NET升级到ASP.NET Core之后,相信大家都会遇到HttpContext.Current无法使用的问题.这也是我们迁移ASP.NET Core必须解决的问题. 本文我们详细讨论一下, ...
- ASP.NET Core on K8S学习之旅(12)Ingress
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 一.关于Ingress Kubernetes对外暴露Service主要有三种方 ...
- 程序员节应该写博客之.NET下使用HTTP请求的正确姿势
程序员节应该写博客之.NET下使用HTTP请求的正确姿势 一.前言 去年9月份的时候我看到过外国朋友关于.NET Framework下HttpClient缺陷的分析后对HttpClient有了一定的了 ...
- .NET Core on K8S学习实践系列文章索引(Draft版)
一.关于这个系列 自从去年(2018年)底离开工作了3年的M公司加入X公司之后,开始了ASP.NET Core的实践,包括微服务架构与容器化等等.我们的实践是渐进的,当我们的微服务数量到了一定值时,发 ...
- ASP.NET Core on K8S深入学习(11)K8S网络知多少
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 一.Kubernetes网络模型 我们都知道Kubernetes作为容器编排引 ...
- ASP.NET Core on K8S深入学习(10)K8S包管理器Helm
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 一.关于Helm 1.1 为何需要Helm? 虽然K8S能够很好地组织和编排容 ...
- .NET下使用HTTP请求的正确姿势
来源:Lewis.Zou cnblogs.com/modestmt/p/7724821.html 一.前言 去年9月份的时候我看到过外国朋友关于.NET Framework下HttpClient缺陷的 ...
随机推荐
- js - 使用jquery发送前台请求给服务器,并显示数据
1.使用jquery发送前台请求给服务器,并显示数据 <%@ page contentType="text/html;charset=UTF-8" language=&quo ...
- mysql 不同版本下 group by 组内排序的差异
最近发现网上找的 group by 组内排序语句在不同的mysql版本中结果不一样. 建表语句: SET FOREIGN_KEY_CHECKS=0; -- ---------------- ...
- 神奇的 SQL 之 CASE表达式,妙用多多 !
前言 历史考试选择题:黄花岗起义第一枪谁开的? A宋教仁 B孙中山 C黄兴 D徐锡麟,考生选C. 又看第二题:黄花岗起义第二枪谁开的? 考生傻了,就选了个B. 接着看第三题:黄花岗起义中,第三枪谁开的 ...
- Waiting for 1 instance(s) to be deallocated
看是不是马虎,自己的xampp,也就是mysql有没有打开
- About dycf
SYSU 数媒在读 所有资料可能与课程相关可能与参与项目相关 欢迎交流 . . . 中之人: ↓↓↓ ↑↑↑ 是他 就是他 ↑↑↑
- 非UI线程更新界面
package com.caterSys.Thread; import java.text.SimpleDateFormat; import java.util.Date; import org.ec ...
- MySQL操作命令梳理(1)
一.索引 1.创建索引 索引的创建可以在CREATE TABLE语句中进行,也可以单独用CREATE INDEX或ALTER TABLE来给表增加索引.以下命令语句分别展示了如何创建主键索引(PRIM ...
- hadoop的基础思想
转载 http://www.superwu.cn/2014/01/10/963 1.1.1. hadoop的核心思想 Hadoop包括两大核心,分布式存储系统和分布式计算系统.1.1.1.1. 分布式 ...
- pycharm的安装配置及思维导图
1.1 计算机基础知识 主板:人的骨架,用于扩展设备的 cpu:人的大脑,用于计算和逻辑处理的 硬盘:存储数据(永久存储) 电源:人的心脏 内存:存储数据(临时存储) 断电即消失 操作系统 xp wi ...
- CPU中的cache结构以及cache一致性
一. 引子 在多线程环境中,经常会有一些计数操作,用来统计线上服务的一些qps.平均延时.error等.为了完成这些统计,可以实现一个多线程环境下的计数器类库,方便记录和查看用户程序中的各类数值.在实 ...