15-K8S Basic-ConfigMap、Secret资源(Pod配置中心)

一、配置容器内的应用程序

  • 配置应用程序是很常见的需求,常用的配置途径是使用配置文件或命令行选项;
  • 但是容器化应用基于镜像文件启动,其配置方式有别于此两种途径;
  • 常用的方法有:
    • 将设置好的配置文件硬编码进镜像文件中
    • 环境变量
      • Docker环境变量 : Dockerfile中定义;
      • Kubernetes环境变量 :资源配置文件中定义
      • 使用kubernetes的ConfigMap和Secret实现集中式配置(配置中心)

  • 在日常单机甚至集群状态下,我们需要对一个应用进行配置,只需要修改其配置文件即可。那么在容器中又该如何提供配置 信息呢???例如,为Nginx配置一个指定的server_name或worker进程数,为Tomcat的JVM配置其堆内存大小。
  • 传统的实践过程中通常有以下几种方式:
    • 启动容器时,通过命令传递参数
    • 将定义好的配置文件通过镜像文件进行写入
    • 通过环境变量的方式传递配置数据
    • 挂载Docker卷传送配置文件
  • 而在Kubernetes系统之中也存在这样的组件,就是特殊的存储卷类型。其并不是提供pod存储空间,而是给管理员或用户提供从集群外部向Pod内部的应用注入配置信息的方式。
  • 这两种特殊类型的存储卷分别是:configMap和secret(以下两种配置方式可以做到不重启pod自动更新配置)。
    • Secret:用于向Pod传递敏感信息,比如密码,私钥,证书文件等,这些信息如果在容器中定义容易泄露,Secret资源可以让用户将这些信息存储在急群众,然后通过Pod进行挂载,实现敏感数据和系统解耦的效果(使用base64进行了编码)。
    • ConfigMap:主要用于向Pod注入非敏感数据,使用时,用户将数据直接存储在ConfigMap对象当中,然后Pod通过使用ConfigMap卷进行引用,实现容器的配置文件集中定义和管理。

二、ConfigMap

2.1、ConfigMap解析

  • configmap是让配置文件从镜像中解耦,让镜像的可移植性和可复制性。许多应用程序会从配置文件、命令行参数或环境变量中读取配置信息。这些配置信息需要与docker image解耦,你总不能每修改一个配置就重做一个image吧?ConfigMap API给我们提供了向容器中注入配置信息的机制,ConfigMap可以被用来保存单个属性,也可以用来保存整个配置文件或者JSON二进制大对象。
  • ConfigMap API资源用来保存key-value pair配置数据,这个数据可以在pods里使用,或者被用来为像controller一样的系统组件存储配置数据。虽然ConfigMap跟Secrets类似,但是ConfigMap更方便的处理不含敏感信息的字符串。 注意:ConfigMaps不是属性配置文件的替代品。ConfigMaps只是作为多个properties文件的引用。可以把它理解为Linux系统中的/etc目录,专门用来存储配置文件的目录。下面举个例子,使用ConfigMap配置来创建Kuberntes Volumes,ConfigMap中的每个data项都会成为一个新文件。
~]# kubectl explain cm
KIND:     ConfigMap
VERSION:  v1            # 标准K8S资源
 
DESCRIPTION:
     ConfigMap holds configuration data for pods to consume.
 
FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
 
   binaryData   <map[string]string>
     BinaryData contains the binary data. Each key must consist of alphanumeric
     characters, '-', '_' or '.'. BinaryData can contain byte sequences that are
     not in the UTF-8 range. The keys stored in BinaryData must not overlap with
     the ones in the Data field, this is enforced during validation process.
     Using this field will require 1.10+ apiserver and kubelet.
 
   data <map[string]string>
     Data contains the configuration data. Each key must consist of alphanumeric
     characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use
     the BinaryData field. The keys stored in Data must not overlap with the
     keys in the BinaryData field, this is enforced during validation process.
 
   immutable    <boolean>
     Immutable, if set to true, ensures that data stored in the ConfigMap cannot
     be updated (only object metadata can be modified). If not set to true, the
     field can be modified at any time. Defaulted to nil. This is an alpha field
     enabled by ImmutableEphemeralVolumes feature gate.
 
   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
 
   metadata <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

2.2、ConfigMap创建及引用方式说明

  • ConfigMap创建方式 :
    • 通过 --from-literal
      • 直接命令行给出,每个 --from-literal 对应一个信息条目。
    • 通过 --from-file
      • 从文件中加载,每个文件内容对应一个信息条目。(默认为文件名称为key,文件内容为value)
    • yaml格式的配置清单
  • ConfigMap引用方式 :
    • 基于存储卷方式引用ConfigMap (pod.spec.volumes.cnfigMap)
    • 基于变量方式引用ConfigMap (env)

2.3、Filebeat-pod创建实战(ConfigMap)

2.3.1、ConfigMap创建 → --from-literal

通过 --from-literal : 直接命令行给出,每个 --from-literal 对应一个信息条目;

1、查看configmap创建命令帮助
    ~]# kubectl create cm -h
 
2、创建一个演示的namespace
    ~]# kubectl create ns config
        namespace/config created
 
3、在此名称空间下创建一个ConfigMap使用命令行直接方式给出key/value
        redis_host="redis.default.svc.cluster.local"     # 使用名称空间+service名称+pod地址
        log_level="Info"
                                  # 定义configmap名称及名称空间          key         value
    ~]# kubectl create configmap filebeat-cfg -n config --from-literal=redis_host="redis.default.svc.cluster.local" --from-literal=log_level="Info"
        configmap/filebeat-cfg created
 
4、获取创建的configmap信息及详细信息
    ~]# kubectl get cm -n config
        NAME           DATA   AGE
        filebeat-cfg   2      92s
# 查看yaml格式信息
~]# kubectl get cm -n config -o yaml
apiVersion: v1
items:
- apiVersion: v1
  data:             # 命令行定义的key/value信息
    log_level: Info
    redis_host: redis.default.svc.cluster.local
  kind: ConfigMap
  metadata:
    creationTimestamp: "2020-05-20T05:50:56Z"
    managedFields:
    - apiVersion: v1
      fieldsType: FieldsV1
      fieldsV1:
        f:data:
          .: {}
          f:log_level: {}
          f:redis_host: {}
      manager: kubectl
      operation: Update
      time: "2020-05-20T05:50:56Z"
    name: filebeat-cfg
    namespace: config
    resourceVersion: "5237575"
    selfLink: /api/v1/namespaces/config/configmaps/filebeat-cfg
    uid: c0f3fa1f-5136-4673-8111-531322356eb6
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

2.3.2、定义Pod引用ConfigMap

  • ConfigMap引用方式 :
    • 基于存储卷方式引用ConfigMap (pod.spec.volumes.configMap)
    • 基于变量方式引用ConfigMap (env)

2.3.2.1、基于变量引用方式使得Pod引用ConfigMap

  • kubectl explain pod.spec.containers
    • env : 自己指定环境变量
      • value : 直接给定值
      • valueFrom : 通过一个位置来引用值
        • configMapKeyRef
          • key : 引用的configmap中的key名称
          • name : 指定引用的configmap名称
          • optional : 此引用是否为可选即有此变量或无此变量都不影响启动,默认为非可选必须值
        • secretKeyRef
    • envFrom : 从另外一个地方加载环境变量
1、创建pod资源配置清单
 
 
configmap]# pwd
/root/mainfests/configmap
 
 
configmap]# cat config-pod.yaml
apiVersion: v1
kind: Pod
# 定义元数据
metadata:
  # pod名称
  name: pod-cfg-demo
  # 名称空间需要和ConfigMap在同一空间下
  namespace: config
  labels:
    app: redis
# 定义pod规格
spec:
  # 定义pod中运行的容器
  containers:
  - name: filebeat
    image: ikubernetes/filebeat:5.6.5-alpine
    # 指定变量引用方式传值
    env:
    # 指定容器中所接受的变量名称
    - name: REDIS_HOST
      # 之前使用的方式为value: xxxx, 现在需要使用通过一个位置来引用值
      valueFrom:
        # 使用ConfigMap方式引用变量
        configMapKeyRef:
          # 指定引用的configmap名称
          name: filebeat-cfg
          # configmap中此前定义的对应的key名称
          key: redis_host
    - name: LOG_LEVEL
      valueFrom:
        configMapKeyRef:
          name: filebeat-cfg
          key: log_level
 
 
 
2、使用声明式接口创建pod资源
    configmap]# kubectl apply -f config-pod.yaml
        pod/pod-cfg-demo created
 
 
3、查看创建的pod信息
    configmap]# kubectl get pods -n config -o wide
        NAME           READY   STATUS    RESTARTS   AGE   IP            NODE        NOMINATED NODE   READINESS GATES
        pod-cfg-demo   1/1     Running   0          69s   10.244.2.32   k8s.node2   <none>           <none>
 
4、连入pod验证变量是否传入成功
    configmap]# kubectl exec -it pod-cfg-demo -n config -- /bin/sh
    / # printenv
        KUBERNETES_PORT=tcp://10.96.0.1:443
        KUBERNETES_SERVICE_PORT=443
        LOG_LEVEL=Info                                  # 传入的变量
        HOSTNAME=pod-cfg-demo
        SHLVL=1
        HOME=/root
        TERM=xterm
        KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
        PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
        KUBERNETES_PORT_443_TCP_PORT=443
        KUBERNETES_PORT_443_TCP_PROTO=tcp
        KUBERNETES_SERVICE_PORT_HTTPS=443
        KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
        PWD=/
        KUBERNETES_SERVICE_HOST=10.96.0.1
        REDIS_HOST=redis.default.svc.cluster.local          # 传入的变量
        FILEBEAT_VERSION=5.6.5
 
5、测试修改ConfigMap键值
configmap]# kubectl edit cm filebeat-cfg -n config
 
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  log_level: Notice         # 将info修改为notice
  redis_host: redis.default.svc.cluster.local
kind: ConfigMap
metadata:
  creationTimestamp: "2020-05-20T05:50:56Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:log_level: {}
        f:redis_host: {}
    manager: kubectl
    operation: Update
    time: "2020-05-20T07:06:17Z"
  name: filebeat-cfg
  namespace: config
  resourceVersion: "5248951"
  selfLink: /api/v1/namespaces/config/configmaps/filebeat-cfg
  uid: c0f3fa1f-5136-4673-8111-531322356eb6
 
configmap]# kubectl edit cm filebeat-cfg -n config
configmap/filebeat-cfg edited
 
6、查看更改后的ConfigMap键值信息
configmap]# kubectl get cm filebeat-cfg -n config -o yaml
apiVersion: v1
data:
  log_level: Notice
  redis_host: redis.default.svc.cluster.local
kind: ConfigMap
metadata:
  creationTimestamp: "2020-05-20T05:50:56Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:log_level: {}
        f:redis_host: {}
    manager: kubectl
    operation: Update
    time: "2020-05-20T07:06:17Z"
  name: filebeat-cfg
  namespace: config
  resourceVersion: "5248951"
  selfLink: /api/v1/namespaces/config/configmaps/filebeat-cfg
  uid: c0f3fa1f-5136-4673-8111-531322356eb6
 
7、此时重建pod,再次连入验证传入的变量信息
    configmap]# kubectl delete -f config-pod.yaml
        pod "pod-cfg-demo" deleted
 
    configmap]# kubectl apply -f config-pod.yaml
        pod/pod-cfg-demo created
 
    configmap]# kubectl exec -it pod-cfg-demo -n config -- /bin/sh
    / # printenv
        KUBERNETES_SERVICE_PORT=443
        KUBERNETES_PORT=tcp://10.96.0.1:443
        LOG_LEVEL=Notice                # 日志级别信息已经发生修改
        HOSTNAME=pod-cfg-demo
        SHLVL=1
        HOME=/root
        TERM=xterm
        KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
        PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
        KUBERNETES_PORT_443_TCP_PORT=443
        KUBERNETES_PORT_443_TCP_PROTO=tcp
        KUBERNETES_SERVICE_PORT_HTTPS=443
        KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
        PWD=/
        KUBERNETES_SERVICE_HOST=10.96.0.1
        REDIS_HOST=redis.default.svc.cluster.local
        FILEBEAT_VERSION=5.6.5

2.4、Nginx-pod创建实战(ConfigMap)

2.4.1、定义Nginx配置文件

#配置文件1
 
 
configmap]# cat server1.conf
server {
 
    server_name www.daizhe.net.cn;
    listen 80;
    location / {
        root "/usr/share/nginx/html";
    }
}
 
 
 
 
#配置文件2
 
 
configmap]# cat server2.conf
server {
 
    server_name top.toptops.top;
    listen 8080;
    location / {
        root "/usr/share/nginx/www";
    }
}

2.4.2、将Nginx配置文件示例定义为ConfigMap → --from-file

1、在此名称空间下创建一个ConfigMap使用从文件中读取key/value
    # --from-file=server1.conf    key名称为配置文件名称,值为配置文件中的信息
    # --from-file=server-second.conf=server2.conf   key名称人为指定为server-second.conf,值为配置文件中的信息(自定义键名称)
     
    configmap]# kubectl create configmap nginx-cfg --from-file=server1.conf --from-file=server-second.conf=server2.conf -n config
        configmap/nginx-cfg created
 
2、获取创建的configmap信息及详细信息
configmap]# kubectl get cm -n config     # 删除使用 kubectl delete cm nginx-cfg -n config
NAME           DATA   AGE
filebeat-cfg   2      105m
nginx-cfg      2      31s
 
 
configmap]# kubectl get cm -n config -o yaml
apiVersion: v1
items:
- apiVersion: v1
  data:
    log_level: Notice
    redis_host: redis.default.svc.cluster.local
  kind: ConfigMap
  metadata:
    creationTimestamp: "2020-05-20T05:50:56Z"
    managedFields:
    - apiVersion: v1
      fieldsType: FieldsV1
      fieldsV1:
        f:data:
          .: {}
          f:log_level: {}
          f:redis_host: {}
      manager: kubectl
      operation: Update
      time: "2020-05-20T07:06:17Z"
    name: filebeat-cfg
    namespace: config
    resourceVersion: "5248951"
    selfLink: /api/v1/namespaces/config/configmaps/filebeat-cfg
    uid: c0f3fa1f-5136-4673-8111-531322356eb6
- apiVersion: v1
  data:
    server-second.conf: "server {\n\n\tserver_name top.toptops.top;\n\tlisten 8080;\n\tlocation
      / {\n\t\troot \"/usr/share/nginx/www\";\n\t}\n}\n"
    server1.conf: "server {\n\n\tserver_name www.daizhe.net.cn;\n\tlisten 80;\n\tlocation
      / {\n\t\troot \"/usr/share/nginx/html\";\n\t}\n}\n"
  kind: ConfigMap
  metadata:
    creationTimestamp: "2020-05-20T07:35:48Z"
    managedFields:
    - apiVersion: v1
      fieldsType: FieldsV1
      fieldsV1:
        f:data:
          .: {}
          f:server-second.conf: {}
          f:server1.conf: {}
      manager: kubectl
      operation: Update
      time: "2020-05-20T07:35:48Z"
    name: nginx-cfg
    namespace: config
    resourceVersion: "5253425"
    selfLink: /api/v1/namespaces/config/configmaps/nginx-cfg
    uid: 4526e9ec-a698-423c-b49f-3d9ed22d306d
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

2.4.3、定义Pod引用ConfigMap

  • ConfigMap引用方式 :
    • 基于存储卷方式引用ConfigMap
    • 基于变量方式引用ConfigMap

2.4.3.1、基于存储卷引用方式使得Pod引用ConfigMap

  • kubectl explain pods.spec.volumes.configMap
    • name : 指定configMap资源名称
    • items : 打算将此configMap中的哪个键映射为配置文件
      • key : 指定引用键名称
      • mode : 映射为文件的权限,如果未设置权限的话,则defaultMode生效
      • path : 映射的文件路径,必须为相对路径
    • defaultMode : 映射为配置文件后的权限为多少 默认为文件权限为0644,目录权限为0777
    • optional : 此引用是否为可选即有此变量或无此变量都不影响启动,默认为非可选必须值
1、创建pod资源配置清单
 
 
configmap]# cat config-pod2.yaml
apiVersion: v1
kind: Pod
# 定义元数据
metadata:
  # pod名称
  name: myapp-pod
  # 名称空间需要和ConfigMap在同一空间下
  namespace: config
  labels:
    app: redis
# 定义pod规格
spec:
  # 定义pod中运行的容器
  containers:
  - name: myapp
    image: nginx:1.14-alpine
    # 定义pod中容器的挂载卷
    volumeMounts:
    # 指定下面定义的挂载卷名称
    - name: config
      # 指定容器的挂载点
      mountPath: /etc/nginx/conf.d/
  # 定义pod中可使用的挂载卷
  volumes:
  # 指定挂载卷名称
  - name: config
    # 定义挂载卷类型
    configMap:
      # 指定事先创建好的configmap名称
      name: nginx-cfg
      # 引用此configmap中的哪个键
      items:
      # 指定引用的键名
      - key: server1.conf
        # 映射到容器中的文件名称(如果不指定则和原始配置同名)
        path: server-first.conf
      - key: server-second.conf
        path: server-second..conf
 
 
 
2、使用声明式接口创建pod资源
    configmap]# kubectl apply -f config-pod2.yaml
        pod/myapp-pod created
 
3、查看创建的pod信息
    configmap]# kubectl get pods -n config -o wide
        NAME           READY   STATUS    RESTARTS   AGE   IP            NODE        NOMINATED NODE   READINESS GATES
        myapp-pod      1/1     Running   0          10s   10.244.2.36   k8s.node2   <none>           <none>
 
4、连入pod验证配置是否引用成功
    configmap]# kubectl exec -it myapp-pod -n config -- /bin/sh
    / # ls /etc/nginx/conf.d/
    / # ls /etc/nginx/conf.d/
        server-first.conf    server-second..conf        # 文件类型为符号链接
 
    / # netstat -tnlp
        Active Internet connections (only servers)
        Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name   
        tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      1/nginx: master pro
        tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1/nginx: master pro
 
5、修改ConfigMap键值文件验证是否生效
configmap]# kubectl edit cm nginx-cfg -n config
 
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
  server-second.conf: "server {\n\n\tserver_name top.toptops.top;\n\tlisten 8081;\n\tlocation       # 8080 --> 8081
    / {\n\t\troot \"/usr/share/nginx/www\";\n\t}\n}\n"
  server1.conf: "server {\n\n\tserver_name www.daizhe.net.cn;\n\tlisten 81;\n\tlocation             # 80 --> 81
    / {\n\t\troot \"/usr/share/nginx/html\";\n\t}\n}\n"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-05-20T08:19:53Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:server-second.conf: {}
        f:server1.conf: {}
    manager: kubectl
    operation: Update
    time: "2020-05-20T08:26:00Z"
  name: nginx-cfg
  namespace: config
  resourceVersion: "5261094"
  selfLink: /api/v1/namespaces/config/configmaps/nginx-cfg
  uid: 7e4ab13c-6eb4-4e25-b425-2b4afdae50fd
 
6、pod会在大约1分钟左右会重新读取配置文件并重新加载(无需删除再次创建pod就可完成配置文件更新)
    configmap]# kubectl exec -it myapp-pod -n config -- /bin/sh
/ # cat /etc/nginx/conf.d/server-first.conf
server {
 
    server_name www.daizhe.net.cn;
    listen 81;
    location / {
        root "/usr/share/nginx/html";
    }
}
 
/ # cat /etc/nginx/conf.d/server-second..conf
server {
 
    server_name top.toptops.top;
    listen 8081;
    location / {
        root "/usr/share/nginx/www";
    }
}
/ # nginx -s reload
2020/05/20 08:30:33 [notice] 82#82: signal process started
/ # netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name   
tcp        0      0 0.0.0.0:8081            0.0.0.0:*               LISTEN      1/nginx: master pro
tcp        0      0 0.0.0.0:81              0.0.0.0:*               LISTEN      1/nginx: master pro
 
 
# 如果有很多个pod副本都通知加载此一个configmap配置文件则就类似于一个同一的配置文件配置中心概念
    非容器化应用程序如果想使用配置文件中心化(需开发者应用程序支持配置文件集中)
        项目:
            Apollo --> 携程
            Distconf --> 百度

2.5、ConfigMap博客鉴赏

2.5.1、ConfigMap创建方式

2.5.1.1、通过 --from-literal:

每个 --from-literal 对应一个信息条目;

[root@k8s-master volumes]# kubectl create configmap nginx-config --from-literal=nginx_port=80 --from-literal=server_name=myapp.magedu.com
configmap/nginx-config created
[root@k8s-master volumes]# kubectl get cm
NAME           DATA      AGE
nginx-config   2         6s
[root@k8s-master volumes]# kubectl describe cm nginx-config
Name:         nginx-config
Namespace:    default
Labels:       <none>
Annotations:  <none>
 
Data
====
server_name:
----
myapp.magedu.com
nginx_port:
----
80
Events:  <none>

2.5.1.2、通过 --from-file:

每个文件内容对应一个信息条目;

[root@k8s-master mainfests]# mkdir configmap && cd configmap
[root@k8s-master configmap]# vim www.conf
server {
    server_name myapp.magedu.com;
    listen 80;
    root /data/web/html;
}
[root@k8s-master configmap]# kubectl create configmap nginx-www --from-file=./www.conf
configmap/nginx-www created
[root@k8s-master configmap]# kubectl get cm
NAME           DATA      AGE
nginx-config   2         3m
nginx-www      1         4s
[root@k8s-master configmap]# kubectl get cm nginx-www -o yaml
apiVersion: v1
data:
  www.conf: "server {\n\tserver_name myapp.magedu.com;\n\tlisten 80;\n\troot /data/web/html;\n}\n"
kind: ConfigMap
metadata:
  creationTimestamp: 2018-10-10T08:50:06Z
  name: nginx-www
  namespace: default
  resourceVersion: "389929"
  selfLink: /api/v1/namespaces/default/configmaps/nginx-www
  uid: 7c3dfc35-cc69-11e8-801a-000c2972dc1f

2.5.2、如何使用configMap

2.5.2.1、环境变量方式注入到pod

[root@k8s-master configmap]# vim pod-configmap.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-cm-1
  namespace: default
  labels:
    app: myapp
    tier: frontend
  annotations:
    magedu.com/created-by: "cluster admin"
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
    ports:
    - name: http
      containerPort: 80
    env:
    - name: NGINX_SERVER_PORT
      valueFrom:
        configMapKeyRef:
          name: nginx-config
          key: nginx_port
    - name: NGINX_SERVER_NAME
      valueFrom:
        configMapKeyRef:
          name: nginx-config
          key: server_name
[root@k8s-master configmap]# kubectl apply -f pod-configmap.yaml
pod/pod-cm-1 created
[root@k8s-master configmap]# kubectl exec -it pod-cm-1 -- /bin/sh
/ # echo $NGINX_SERVER_PORT
80
/ # echo $NGINX_SERVER_NAME
myapp.magedu.com
 
 
# 修改端口,可以发现使用环境变化注入pod中的端口不会根据配置的更改而变化
 
 
[root@k8s-master volumes]#  kubectl edit cm nginx-config
configmap/nginx-config edited
/ # echo $NGINX_SERVER_PORT
80

2.5.2.2、存储卷方式挂载configmap:Volume 形式的 ConfigMap 也支持动态更新

[root@k8s-master configmap ~]# vim pod-configmap-2.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-cm-2
  namespace: default
  labels:
    app: myapp
    tier: frontend
  annotations:
    magedu.com/created-by: "cluster admin"
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
    ports:
    - name: http
      containerPort: 80
    volumeMounts:
    - name: nginxconf
      mountPath: /etc/nginx/config.d/
      readOnly: true
  volumes:
  - name: nginxconf
    configMap:
      name: nginx-config
[root@k8s-master configmap ~]# kubectl apply -f pod-configmap-2.yaml
pod/pod-cm-2 created
[root@k8s-master configmap ~]# kubectl get pods
[root@k8s-master configmap ~]# kubectl exec -it pod-cm-2 -- /bin/sh
/ # cd /etc/nginx/config.d
/ # cat nginx_port
80
/ # cat server_name
myapp.magedu.com
 
[root@k8s-master configmap ~]# kubectl edit cm nginx-config  #修改端口,再在容器中查看端口是否变化。
apiVersion: v1
data:
  nginx_port: "800"
  ......
   
/ # cat nginx_port
800
[root@k8s-master configmap ~]# kubectl delete -f pod-configmap2.yaml

2.5.2.3、以nginx-www配置nginx

[root@k8s-master configmap ~]# vim pod-configmap3.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod-cm-3
  namespace: default
  labels:
    app: myapp
    tier: frontend
  annotations:
    magedu.com/created-by: "cluster admin"
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
    ports:
    - name: http
      containerPort: 80
    volumeMounts:
    - name: nginxconf
      mountPath: /etc/nginx/conf.d/
      readOnly: true
  volumes:
  - name: nginxconf
    configMap:
      name: nginx-www
[root@k8s-master configmap ~]# kubectl apply -f pod-configmap3.yaml
pod/pod-cm-3 created
[root@k8s-master configmap ~]# kubectl get pods
[root@k8s-master configmap]# kubectl exec -it pod-cm-3 -- /bin/sh
/ # cd /etc/nginx/conf.d/
/etc/nginx/conf.d # ls
www.conf
/etc/nginx/conf.d # cat www.conf
server {
    server_name myapp.magedu.com;
    listen 80;
    root /data/web/html;
}
posted @ 2021-06-20 12:21  SRE运维充电站  阅读(3)  评论(0编辑  收藏  举报