写点什么

一文带你弄懂 Kubernetes 应用配置管理时间

作者:Java-fenn
  • 2022 年 9 月 09 日
    湖南
  • 本文字数:6580 字

    阅读完需:约 22 分钟

主题

Kubernetes YAML


不论什么样的应用,基本都有配置文件,在企业中,大部分会用到配置中心,比如 apollo、nacos 等,也有一些公司直接使用 Kubernetes 自带的配置管理,主要有:


SecretConfigMapSecret 如果把配置信息保存在 Secret 中,其会被加密存放到 Etcd 中,Pod 可以通过以下两种种方式使用它:


通过环境变量的方式通过挂载的方式指定拉取镜像的 Secret 一般情况下,通过 Secret 保存的配置信息都是敏感信息,比如数据库的账号密码、认证服务的账号密码等,且 Secret 不宜过大,因为如果使用大的 Secret,则将大量占用 API Server 和 kubelet 的内存。


创建 Secret 创建 Secret 的方式主要有两种:


使用 YAML 文件创建使用 kubectl 命令创建使用 YAML 文件创建使用 YAML 文件创建,就要熟悉 Secret 的配置详情,可以通过 kubectl explain secret 去查看。其主要字段有 apiVersion,data,kind,metadata,type。


比如创建一个简单的 Secret 如下:


apiVersion: v1kind: Secretmetadata:name: my-secret-volumetype: Opaquedata:user: cm9vdA==password: UEBzc1cwcmQ=其中 apiVersion、kind 和 metadata 是常用字段,这里就不赘述了。type 表示 secret 的类型,主要有以下几种:


Qpaque:可以定义任意数据。kubernetes.io/service-account-token:配置 ServiceAccount Token。kubernetes.io/dockercfg:配置 docker 认证文件。kubernetes.io/dockerconfigjson:配置 docker 认证文件。kubernetes.io/basic-auth:配置基础认证。kubernetes.io/ssh-auth:配置 ssh 认证。kubernetes.io/tls:配置 TLS 证书。bootstrap.kubernetes.io/token:配置 bootstrap token。如果在创建 Secret 的时候没有指定类型,默认使用 Qpaque 类型。另外 data 的数据的值是需要 base64 转码。


使用 kubectl 命令创建在使用 kubectl 创建的时候,如果不熟悉子命令信息,可以通过 kubectl explain secret 查看。


我们使用以下命令创建一个 Secret:


$ kubectl create secret generic secret-auth-test --from-literal=username=joker --from-literal=password=123 创建完成后,可以看到 username 和 password 的值被自动加密了,如下:


$ kubectl get secrets secret-auth-test -oyamlapiVersion: v1data:password: MTIzusername: am9rZXI=kind: Secretmetadata:creationTimestamp: "2022-07-25T07:44:18Z"name: secret-auth-testnamespace: defaultresourceVersion: "652834"uid: ff1b756a-6b38-4b68-a47c-c51988729b68type: Opaque 除了直接在命令行输入数据,还可以从文件创建,如下:


echo -n '1f2d1e2e67df' > ./password.txt 然后通过--from-file 引入文件,如下:


$ kubectl create secret generic db-user-pass


--from-file=./username.txt


--from-file=./password.txt 创建后的 secret 值都是加密的,如果要获取明文信息,通过以下命令即可:


$ kubectl get secret db-user-pass -o jsonpath='{.data.password}' | base64 --decode 默认情况下,secret 是使用 base64 加密的,所以解密可以直接使用 base64 解密。


使用 SecretSecret 只是一个静态资源,最终,我们是想使用它,在实际中,主要通过以下方式使用:


通过环境变量的方式。通过挂载的方式。指定拉取镜像的 Secret。我们在上面创建了 secret-auth-test 的 Secret,下面分别使用以上三种方式进行使用。


通过环境变量使用 Secret 在 Pod 的对象中,有 spec.containers.env.valueFrom.secretKeyRef 字段,该字段可以用来引用 Secret 字段,如下:


apiVersion: v1kind: Podmetadata:name: secret-env-podspec:containers:


  • name: mycontainerimage: redisenv:

  • name: SECRET_USERNAMEvalueFrom:secretKeyRef:name: secret-auth-testkey: username

  • name: SECRET_PASSWORDvalueFrom:secretKeyRef:name: secret-auth-testkey: password 这样就会把 Secret 里的信息注入到容器环境变量里,应用可以直接通过读取环境变量来使用。


通过挂载的方式使用 Secret 可以使用挂载的方式,将 Secret 以文件的形式挂载到容器中,如下:


apiVersion: v1kind: Podmetadata:name: mypodspec:containers:


  • name: mypodimage: redisvolumeMounts:

  • name: foomountPath: "/etc/foo"readOnly: truevolumes:

  • name: foosecret:secretName: secret-auth-test 这样就会把数据挂载到/etc/foo 这个目录里,如下:


$ kubectl exec -it mypod -- /bin/sh

ls -l /etc/foo

total 0lrwxrwxrwx 1 root root 15 Jul 25 08:30 password -> ..data/passwordlrwxrwxrwx 1 root root 15 Jul 25 08:30 username -> ..data/username 如果 Secret 里有多个键值,还可以只挂载某一个数据,如下:


apiVersion: v1kind: Podmetadata:name: mypodspec:containers:


  • name: mypodimage: redisvolumeMounts:

  • name: foomountPath: "/etc/foo"readOnly: truevolumes:

  • name: foosecret:secretName: secret-auth-testitems:

  • key: usernamepath: my-group/my-username 上面指定 volumes.secret.items.path 用来指定 username 的子目录,如下:


$ kubectl exec -it mypod-password -- /bin/bash


root@mypod-password:/data# cat /etc/foo/my-group/my-usernamejoker 除此之外,还可以指定权限,如下:


apiVersion: v1kind: Podmetadata:name: mypodspec:containers:


  • name: mypodimage: redisvolumeMounts:

  • name: foomountPath: "/etc/foo"volumes:

  • name: foosecret:secretName: secret-auth-testdefaultMode: 0400 然后可以看到被挂载的 Secret 的权限如下:


$ kubectl exec -it mypod-permision -- /bin/bashroot@mypod-permision:/etc/foo# ls -ltotal 0lrwxrwxrwx 1 root root 15 Jul 25 08:38 password -> ..data/passwordlrwxrwxrwx 1 root root 15 Jul 25 08:38 username -> ..data/usernameroot@mypod-permision:/etc/foo# ls ..data/password -l-r-------- 1 root root 3 Jul 25 08:38 ..data/password 注意:我们进/etc/foo 目录直接使用 ls -l 查看到的权限是 777,但是仔细的人可以发现其实质是一个链接文件,我们真正要看的权限是被链接的文件,也就是上面的..data/password。


在拉取镜像的时候使用 Secret 我们在前面列举了很多 YAML 文件,都没有配置 imagePullSecret,主要是那些镜像都是 Dockerhub 官方的镜像,对外是公开的。


然而,在实际的生产中,不会将自己公司的镜像对外公开,这非常的不安全。如果镜像仓库加密了,在下载镜像的时候要 docker login,在 Kubernetes 中,也免不了该操作。


为此,Kubernetes 提供了 imagePullSecret 字段,该字段用来指定拉取镜像的 Secret,这个 Secret 会保存镜像仓库的认证信息。


(1)首先创建镜像认证信息的 Secret。


kubectl create secret


docker-registry pull-registry-secret


--docker-server=registry.test.cn


--docker-username=ops


--docker-password=ops123123


(2)在 Pod 中使用。


apiVersion: v1kind: Podmetadata:name: mypodspec:imagePullSecrets:


  • name: pull-registry-secretcontainers:

  • name: mypodimage: redisvolumeMounts:

  • name: foomountPath: "/etc/foo"volumes:

  • name: foosecret:secretName: secret-auth-testdefaultMode: 0400 这样就可以拉取私有仓库里的镜像了。


总结综上,我们可以通过 Secret 保管其他系统的敏感信息(比如数据库的用户名和密码),并以 Mount 的方式将 Secret 挂载到 Container 中,然后通过访问目录中文件的方式获取该敏感信息。当 Pod 被 API Server 创建时,API Server 不会校验该 Pod 引用的 Secret 是否存在。一旦这个 Pod 被调度,则 kubelet 将试着获取 Secret 的值。如果 Secret 不存在或暂时无法连接到 API Server,则 kubelet 按一定的时间间隔定期重试获取该 Secret,并发送一个 Event 来解释 Pod 没有启动的原因。一旦 Secret 被 Pod 获取,则 kubelet 将创建并挂载包含 Secret 的 Volume。只有所有 Volume 都挂载成功,Pod 中的 Container 才会被启动。在 kubelet 启动 Pod 中的 Container 后,Container 中和 Secret 相关的 Volume 将不会被改变,即使 Secret 本身被修改。为了使用更新后的 Secret,必须删除旧 Pod,并重新创建一个新 Pod。


ConfigMapConfigMap 和 Serect 类似,不同之处在于 ConfigMap 保存的数据信息是不需要加密的,比如一些应用的配置信息,其他的用法和 Secret 一样。


创建 ConfigMap 同样,我们可以使用两种方式来创建 ConfigMap:


通过命令行方式,也就是 kubectl create configmap。通过 YAML 文件方式;通过命令创建 ConfigMap 如果不熟悉 ConfigMap 对象的字段,可以通过 kubectl explain configmap 来查看,如果想查看创建 configmap 的示例,可以通过 kubectl create configmap -h 查看,如下:


Examples:

Create a new config map named my-config based on folder bar

kubectl create configmap my-config --from-file=path/to/bar

Create a new config map 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 config map 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 config map named my-config from the key=value pairs in the file

kubectl create configmap my-config --from-file=path/to/bar

Create a new config map named my-config from an env file

kubectl create configmap my-config --from-env-file=path/to/foo.env --from-env-file=path/to/bar.env 从上面可以看出,创建 ConfigMap 可以从给定一个目录来创建。例如,我们定义了如下一些配置文件:


cd configmap-demo cat mysqld.confhost=127.0.0.1port=3306$ cat redis.confhost=127.0.0.1port=6379 然后使用一下命令来进行创建:


$ kubectl create configmap my-configmap --from-file=../configmap-demo/然后通过一下命令查看创建完的 configmap:

kubectl describe cm my-configmapName: my-configmapNamespace: defaultLabels: <none>Annotations: <none>Data

mysqld.conf:

host=127.0.0.1port=3306redis.conf:

host=127.0.0.1port=6379BinaryData

Events: <none>我们可以看到两个 key 对应的是文件的名字,value 对应的是文件的内容。如果要看键值的话可以通过如下命令查看:


$ kubectl get configmap my-configmap -o yamlapiVersion: v1data:mysqld.conf: |host=127.0.0.1port=3306redis.conf: |host=127.0.0.1port=6379kind: ConfigMapmetadata:creationTimestamp: "2022-07-25T09:20:43Z"name: my-configmapnamespace: defaultresourceVersion: "667706"uid: 46cb52e9-0936-4934-9628-ac20efcfd893 当然,我们还可以通过文件来创建一个 configmap,比如我们定义一个如下的配置文件:


cat nginx.confuser nobody;worker_processes 1;error_log logs/error.log;error_log logs/error.log notice;error_log logs/error.log info;pid logs/nginx.pid;events {worker_connections 1024;}http {include mime.types;default_type application/octet-stream;log_format main 'remote_addr - time_local] "status http_referer" ''"http_x_forwarded_for"';access_log logs/access.log main;sendfile on;tcp_nopush on;keepalive_timeout 65;gzip on;server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}}然后通过如下命令创建一个 nginx 的 configmap:


$ kubectl create configmap nginx-configmap --from-file=nginx.conf 查看创建后的信息:


kubectl get configmap nginx-configmap -o yamlapiVersion: v1data:nginx.conf: |user nobody;worker_processes 1;error_log logs/error.log;error_log logs/error.log notice;error_log logs/error.log info;pid logs/nginx.pid;events {worker_connections 1024;}http {include mime.types;default_type application/octet-stream;log_format main 'remote_addr - time_local] "status http_referer" ''"http_x_forwarded_for"';access_log logs/access.log main;sendfile on;tcp_nopush on;keepalive_timeout 65;gzip on;server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}}kind: ConfigMapmetadata:creationTimestamp: "2022-07-25T09:24:29Z"name: nginx-configmapnamespace: defaultresourceVersion: "668283"uid: a025da28-6817-4605-8daf-375b676282c1 注:在一条命令中--from-file 可以指定多次。


另外,通过帮助文档我们可以看到我们还可以直接使用字符串进行创建,通过--from-literal 参数传递配置信息,同样的,这个参数可以使用多次,格式如下:


$ kubectl create configmap my-cm-daemo --from-literal=db.host=localhost --from-literal=db.port=3306 通过 YAML 创建 ConfigMap 通过 YAML 文件创建就比较简单,我们可以参考上面输出的 yaml 信息,比如定义如下一个 YAML 文件:


apiVersion: v1kind: ConfigMapmetadata:name: my-cm-daemon2labels:app: cm-daemondata:redis.conf: |host=127.0.0.1port=6379 然后创建即可。


使用 ConfigMapConfigMap 中的配置数据可以通过如下方式进行使用:


设置环境变量值。在数据卷中创建 config 文件。通过环境变量使用 ConfigMap 我们直接通过在 pod.spec.containers.env.valueFrom.configMapKeyRef 中引用 ConfigMap 即可,如下:


apiVersion: v1kind: Podmetadata:name: env-configmaplabels:app: env-configmap-mysqlspec:containers:


  • name: test-configmapimage: busyboxcommand:

  • "/bin/sh"

  • "-c"

  • "env"env:

  • name: DB_HOSTvalueFrom:configMapKeyRef:name: my-cm-daemokey: db.host

  • name: DB_PORTvalueFrom:configMapKeyRef:name: my-cm-daemokey: db.portenvFrom:

  • configMapRef:name: my-cm-daemo 创建后,可以通过日志查看环境变量输出,如下:


$ kubectl logs env-configmap | grep DBDB_PORT=3306DB_HOST=localhost 通过数据卷使用 ConfigMap 基本原理和 Secret 一样。


在这里,通过指定 pod.spec.volumes.configMap.name 来指定 ConfigMap,然后挂载到容器里,如下:


apiVersion: v1kind: Podmetadata:name: volume-configmap-testspec:containers:- name: volume-configmap-testimage: busyboxcommand: [ "/bin/sh", "-c", "cat /etc/config/redis.conf" ]volumeMounts:- name: config-volumemountPath: /etc/configvolumes:- name: config-volumeconfigMap:name: my-configmap 我们可以通过日志查看 ConfigMap 是否挂载进去了。


$ kubectl logs volume-configmap-testhost=127.0.0.1port=6379 我们也可以在 ConfigMap 值被映射的数据卷里去控制路径,如下:


apiVersion: v1kind: Podmetadata:name: volume-path-configmapspec:containers:- name: volume-path-configmap-testimage: busyboxcommand: [ "/bin/sh","-c","cat /etc/config/path/to/msyqld.conf" ]volumeMounts:- name: config-volumemountPath: /etc/configvolumes:- name: config-volumeconfigMap:name: my-configmapitems:- key: mysqld.confpath: path/to/msyqld.conf 另外,当 ConfigMap 以数据卷的形式挂载进 Pod 的时,这时更新 ConfigMap(或删掉重建 ConfigMap),Pod 内挂载的配置信息会热更新。虽然配置信息更新,应用到底能不能使用,主要还是依赖应用是否也会热更新。


总结 ConfigMap 在实际中用的还是比较多,主要都是一些应用的配置文件,比如 Nginx 配置文件,MySQL 配置文件,这类配置文件如果想放到私有的配置中心需要额外花费更多的精力,而放到 ConfigMap,则方便很多,而且多数都以挂载的方式放进容器里。

用户头像

Java-fenn

关注

需要Java资料或者咨询可加我v : Jimbye 2022.08.16 加入

还未添加个人简介

评论

发布
暂无评论
一文带你弄懂Kubernetes应用配置管理时间_java;_Java-fenn_InfoQ写作社区