美文网首页
K8s Configmap 使用

K8s Configmap 使用

作者: 京樂春水 | 来源:发表于2020-04-12 13:57 被阅读0次

    configmap,用来为pod提供配置文件或者环境变量
    创建方法:

    1. 使用yaml文件
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: cm-0412
      labels:
        app: nginx
    data:
      TEST: "0412"
      nginx-conf: |
        server {
          listen       80;
          server_name  localhost;
          #charset koi8-r;
          #access_log  /var/log/nginx/host.access.log  main;
    
          location / {
              root   /usr/share/nginx/html;
              index  index.html index.htm;
          }
    
          location /getWanIp {
                  default_type text/plain;
                  set $ret_addr $remote_addr;
                  if ( $http_x_forwarded_for ~ ^. ) { set $ret_addr "$http_x_forwarded_for, $remote_addr"; }
                  return 200 "$ret_addr\n";
          }
        }
    

    配置文件中,创建了一个"TEST"的环境变量(注意,值必须为string),另外还创建了一个"nginx-conf"的配置文件(注意配置文件的缩进格式,需整体偏移,否则会报错)

    1. 使用命令
      创建配置文件
    kubectl create configmap cm-0412-2 --from-file=nginx-test=nginx.conf (可以把"nginx-test="去掉,这样configmap中的key就是文件名)
    

    创建环境变量

    kubectl create configmap cm-0412-3 --from-literal=halala=wlala
    

    Pod中使用configmap
    Pod配置文件如下:

    apiVersion: v1
    kind: Pod
    metadata:
      name: nginx
      labels:
        name: nginx
    spec:
      containers:
      - name: nginx
        image: nginx、
        # 以环境变量方式使用configmap
        envFrom:
          - configMapRef:
              name: cm-0412-3
        # 以挂载方式使用configmap
        volumeMounts:
          - name: nginx-vl
            mountPath: /etc/nginx/conf.d/
      volumes:
        - name: nginx-vl
          configMap:
              name: cm-0412-2
              items:
                - key: nginx-test
                  # path代表以default.conf这个文件名挂载到pod中
                  path: default.conf
    

    测试结果如下:

    [root@Kurber001 Pod]# curl 10.244.2.107/getWanIp
    10.244.0.0
    [root@Kurber001 Pod]# kubectl exec -it nginx /bin/bash
    root@nginx:/# echo $halala
    wlala
    

    成功~

    PS: 一般YAML文件中的volumeMounts都是挂载到目录,如果需要指定挂载到文件,需要使用"subPath"关键字

    相关文章

      网友评论

          本文标题:K8s Configmap 使用

          本文链接:https://www.haomeiwen.com/subject/xkpvmhtx.html