K8s Configmap 使用

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"關鍵字

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容