configmap是k8s的一个配置管理组件,可以将配置以key-value的形式传递,通常用来保存不需要加密的配置信息,加密信息则需用到Secret,主要用来应对以下场景:
- 使用k8s部署应用,当你将应用配置写进代码中,就会存在一个问题,更新配置时也需要打包镜像,configmap可以将配置信息和docker镜像解耦。
- 使用微服务架构的话,存在多个服务共用配置的情况,如果每个服务中单独一份配置的话,那么更新配置就很麻烦,使用configmap可以友好的进行配置共享。
configmap有三种常见创建方式:
1. 通过yaml / json文件创建(推荐)
apiVersion: v1kind: ConfigMapmetadata:name: test-confnamespace: testdata:test-conf: |+SESSION_LIFETIME: 3600URL: "http://test-server:8080"
2.通过—from-file
分别指定单个文件和目录,指定目录可以创建一个包含该目录中所有文件的configmap:
kubectl create configmap * —from-file=/path
3.通过key-value字符串创建
kubectl create configmap * —from-literal=config1=123 —from-literal=config2=234
onfigmap创建成功之后,如何在pod中使用呢?有以下几种方法:
注意**
使用ConfigMap有以下几个限制条件:
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
volume
通过Volume挂载的方式将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
