k8s系列文章:
configmap是k8s的一個配置管理組件,可以將配置以key-value的形式傳遞,通常用來保存不需要加密的配置信息,加密信息則需用到Secret,主要用來應對以下場景:
- 使用k8s部署應用,當你將應用配置寫進代碼中,就會存在一個問題,更新配置時也需要打包鏡像,configmap可以將配置信息和docker鏡像解耦。
- 使用微服務架構的話,存在多個服務共用配置的情況,如果每個服務中單獨一份配置的話,那麼更新配置就很麻煩,使用configmap可以友好的進行配置共享。
其次,configmap可以用來保存單個屬性,也可以用來保存配置文件。
創建
你可以通過命令kubectl create configmap -h
幫助信息查看具體的創建。
configmap有三種常見創建方式:
1. 通過yaml / json文件創建(推薦)
這種是我比較推薦的方式,創建configmap.yaml:
apiVersion: v1
kind: ConfigMap
metadata:
name: test-conf
namespace: test
data:
test-conf: |+
SESSION_LIFETIME: 3600
URL: "http://test-server:8080"
執行命令:
kubectl create -f configmap.yaml
若報錯:"namespace 'test' not found",則需要先創建namespace:
kubectl create namespace test
2. 通過--from-file
分別指定單個文件和目錄,指定目錄可以創建一個包含該目錄中所有文件的configmap:
kubectl create configmap *** --from-file=/path
將--from-file指定爲單個文件就可以從單個文件中創建:
kubectl create configmap *** --from-file=file1
其中,--from-file可以使用多次,比如:
kubectl create configmap *** --from-file=file1 --from-file=file2
3. . 通過key-value字符串創建
kubectl create configmap *** --from-literal=config1=123 --from-literal=config2=234
4. 通過env文件創建
通過環境文件創建:
kubectl create configmap *** --from-env-file=env.txt
其中,env.txt的文件格式爲:
config1=***
config2=***
當使用多個--from-env-file從多個數據源創建configmap時,僅最後一個env文件有效。
查看
可以使用以下命令查看創建成功的configmap:
命令 | 說明 |
---|---|
kubectl get configmaps | 查看所有configmap |
kubectl get configmaps -n namespace1 | 查看命名空間爲namespace1的所有configmap |
kubectl describe configmaps configmap1 | 查看configmap1的詳細信息 |
kubectl get configmaps configmap1 -o yaml | 以yaml文件形式展示configmap詳細信息 |
使用
configmap創建成功之後,如何在pod中使用呢?有以下幾種方法:
注意
使用ConfigMap有以下幾個限制條件:
- ConfigMap必須在pod之前創建
- configmap受namespace的限制,只能相同namespace的pod纔可以引用
env
通過環境變量獲取ConfigMap中的內容。
首先創建configmap:
kubectl create configmap test-config --from-literal=env_model=prd -n test
接下來用作環境變量,創建pod.yaml:
apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: test
spec:
containers:
- name: test-container
image: test:v0.1
env:
- name: TEST-CONF
valueFrom:
configMapKeyRef:
name: test-config
key: env_model
執行命令創建Pod:
kubectl create -f pod.yaml
創建成功之後,執行命令查看pod的詳細信息,可以看到已經將configmap中的配置添加到環境變量:
kubectl describe pod test-pod -n test
同時,也支持多個configmap共同創建環境變量。
volume
通過Volume掛載的方式將ConfigMap中的內容掛載爲容器內部的文件或目錄,這是我平時用的較多的方式。
接下來使用最開始創建的test-conf爲例說明,將configmap掛載到特定目錄,並保存爲指定文件:
apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: test
spec:
containers:
- name: test-container
image: test:v0.1
volumeMounts:
- name: test-volume
mountpath: /app/config
volumes:
- name: test-volume
configMap:
name:test-conf
items:
- key: test-conf
path: config.yaml
以上。