Docs/CloudNative/Kubernetes/Base/ConfigMap.md
2022-10-18 16:59:37 +08:00

3.5 KiB
Raw Blame History

创建ConfigMap的方法

通过直接在命令行中指定configmap参数创建即--from-literal
通过指定文件创建即将一个配置文件创建为一个ConfigMap--from-file=<文件>
通过指定目录创建即将一个目录下的所有配置文件创建为一个ConfigMap--from-file=<目录>
事先写好标准的configmap的yaml文件然后kubectl create -f 创建

命令行指定参数创建

kubectl create configmap demo_config --from-literal=name=demo --from-literal=version=v1

指定文件创建

kubectl create configmap demo_config --from-file=k1=/path/to/file1 --from-file=k2=/path/to/file2

指定目录创建(以目录下的文件名为键,内容为值)

只识别文件,忽略目录下的子目录

kubectl create configmap demo_config --from-file=k1=/path1  --from-file=/path2

以yaml文件创建

apiVersion: v1
kind: ConfigMap

metadata:
  name: demo_config
  namespace: demo-ns
  
  labels:
    name: demo
    version: v1
    
data:
  name: demo
  version: v1

使用ConfigMap

第一种是通过环境变量的方式直接传递给pod
  使用configmap中指定的key
  使用configmap中所有的key
第二种是通过在pod的命令行下运行的方式(启动命令中)
第三种是作为volume的方式挂载到pod内

valueFrom、configMapKeyRef指定key

apiVersion: v1
kind: Pod

metadata:
  name: pod-demo1
  namespace: demo-ns
  
  labels:
    name: pod-demo1
    version: v1
spec:
  containers:
  - name: demo
    image: demo1
    command:
    - "/bin/sh"
    - "-c"
    - "echo hello demo"
    
    ports:
    - name: demo-http
      containerPort: 80
      protocol:TCP
    
    env:
      valueFrom: 
      - name: CONFIG_ENV
        configMapKeyRef:
          name: demo_config
          key: name

envFrom、configMapRef指定configmap中所有key

apiVersion: v1
kind: Pod

metadata:
  name: pod-demo1
  namespace: demo-ns
  
  labels:
    name: pod-demo1
    version: v1
spec:
  containers:
  - name: demo
    image: demo1
    command:
    - "/bin/sh"
    - "-c"
    - "echo hello demo"
    
    ports:
    - name: demo-http
      containerPort: 80
      protocol:TCP
    
    envFrom:
    - configMapRef:
        name: demo_config

在命令行下引用时,需要先设置为环境变量,之后可以通过$(VAR_NAME)设置容器启动命令的启动参数

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_LEVEL
        - name: SPECIAL_TYPE_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_TYPE
  restartPolicy: Never

作为volume挂载使用

以key为文件名value为内容
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-configmap
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx-configmap
    spec:
      containers:
      - name: nginx-configmap
        image: nginx
        ports:
        - containerPort: 80
        volumeMounts:     
        - name: config-volume4
          mountPath: /tmp/config4
      volumes:
      - name: config-volume4
        configMap:
          name: test-config4