k8s ConfigMap

内容纲要

概述

在我们的业务开发中,我们的应用或者服务需要很多配置,例如:数据库配置(连接url, port, connectionTimeout),redis配置,Spring框架配置等等,同时在不同环境也需要不同的配置。
k8s提供了ConfigMap资源对象为我们的应用提供了非敏感信息配置。

适用场景

ConfigMap的应用场景就是非敏感信息。

创建ConfigMap

创建ConfigMap的方式有很多种,但是我觉得最常用的方式应该是Yaml文件方式。

创建方式

  1. 基于普通文件
  2. 基于字面值
  3. 基于Yaml文件

基于普通文件

假设我们创建一个helloworld.txt,并在文件中输入hello world,如下图所示:
file
使用kubectl命令创建ConfigMap

kubectl create configmap helloworld --from-file=./helloworld.txt

kubectl describe cm/helloworld

file

基于字面值

kubectl create configmap literal-helloworld --from-literal=hello1=world1 --from-literal=hello2=world2

kubectl describe cm/literal-helloworld

file

基于Yaml文件

  1. 创建ConfigMap资源清单文件helloworld.yaml
    kind: ConfigMap
    apiVersion: v1
    metadata:
    name: common-config
    namespace: your_namespace
    data:
    TZ: Asia/Shanghai
    dbInitialSize: '16'
    dbMaxActive: '64'
    dbMaxWait: '60000'
    dbMinIdle: '16'
  2. 在k8s中创建ConfigMap
    kubectl applyl -f helloworld.yaml

ConfigMap的使用方式

  1. 环境变量方式
  2. Volume方式

环境变量方式

  1. env
  2. envFrom

    环境变量的问题可能就是无法直接将ConfigMap中key对应的二进制Value注入到环境变量,一般需要将二进制value进行一次Base64编码。但是经过一次Base64编码后,应用可能无法直接使用这个Value,所以需要应用程序进行一次Base64解码。

env

deployment中引用刚才创建的literal-helloworld中的key和value。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  namespace: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.0
        ports:
        - containerPort: 80
      - env:
        - name: hello
          valueFrom:
            configMapKeyRef:
              key: hello1
              name: literal-helloworld

envFrom

envFrom直接引用ConfigMap中的所有key-value,并且将所有key-value注入到容器环境变量中,在容器启动成功后,使用printenv可以查看所有的key-value

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.14.0
        ports:
        - containerPort: 80
        name: nginx
        envFrom:
          - configMapRef:
              name: literal-helloworld

Volume 方式

Volume方式就是将ConfigMap挂在到容器的文件系统中。

apiVersion: apps/v1  
kind: Deployment  
metadata:  
  labels:  
    app: nginx  
  name: nginx  
  namespace: default  
spec:  
  replicas: 1  
  selector:  
    matchLabels:  
      app: nginx  
  template:  
    metadata:  
      labels:  
        app: nginx  
    spec:  
      containers:  
      - image: nginx:1.14.0  
        ports:  
        - containerPort: 80  
        name: nginx  
        volumeMounts:  
        - name: literal-helloworld-volume  
          mountPath: /path/to/configmap/data  
      volumes:  
      - name: literal-helloworld-volume  
        configMap:  
          name: literal-helloworld

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部