Kubernetes入门(六)配置参数ConfigMap
容器配置参数的三种方式
-
向容器传递命令行参数
ENTRYPOINT["node","xxx.js"] # exec形式 ENTRYPOINT node xxx.js #shell形式,比exec形式多一个shell进程,不推荐
-
容器启动时,设置环境变量参数 通过ConfigMap资源向将配置参数文件挂载到容器内
k8s中覆盖命令和参数
在k8s中定义容器时,镜像中的ENTRYPOINT和CMD参数都可以被覆盖,配置参数为command和args,注意,这两个参数在pod被创建后无法修改
kind: Pod spec: containers: - image: xxx command: ["/bin/command"] args: ["arg1","arg2","arg3"]
pod内指定环境变量
kind: Pod
spec:
containers:
- image: xxx
env: #指定环境变量
- name: FIRST_ENV
value: "12"
- name: SECOND_ENV
value: "$(FIRST_ENV)90" #引用FIRST_ENV的值,即为1290
利用ConfigMap解耦参数配置
ConfigMap是key-value映射对,应用程序无需直接读取ConfigMap,其参数配置通过环境变量或者卷文件的形式传递给容器,从而实现应用程序和参数配置的解耦。 开发与生产环境的ConfigMap分别配置 创建ConfigMap ①命令行方式创建
kubectl create configmap configmap_name --from-literal=config_1=90 --from-literal=config_2=100 --from-literal=config_3=110
ConfigMap
②yaml文件创建 config-file.yaml
apiVersion: v1 data: first_env: 12 metadata: name: configureData
kubectl create -f config-file.conf
③直接读取配置文件config-file.conf config-file.conf
abc
kubectl create configmap configmap_name --from-file=config-file.conf
ConfigMap
④从文件夹创建
kubectl create configmap configmap_name --from-file=foo.json --from-file=bar=foobar.conf --from-file=config-opts/ --from-literal=some=thing
从容器中读取ConfigMap
①使用valueFrom
apiVersion: v1
kind: Pod
metadata:
name: read-env-from-configmap
spec:
containers:
- image: xxx
env:
- name: FIRST_ENV #设置环境变量FIRST_ENV
valueFrom:
configMapRef: #初始化ConfigMap,不使其固定,从而实现动态调整
name: configmap_name # ConfigMap的名字
key: env_value # 引用configmap_name内的环境变量值env_value ,来填充FIRST_ENV
args: ["$(FIRST_ENV)"]#直接引用FIRST_ENV
一次传递所有ConfigMap的值
apiVersion: v1
kind: Pod
metadata:
name: read-env-from-configmap
spec:
containers:
- image: xxx
envFrom:
#- prefix: CONFIG_ #所有的环境变量都包含的前缀名字
configMapRef:
name: configmap_name
②使用ConfigMap卷,将条目作为文件挂载到容器
apiVersion: v1
kind: Pod
metadata:
name: read-env-from-configmap
spec:
containers:
- image: xxx
name: name_xxx
volumeMounts:
- name: config
mountPath: /etc/nginx/config.d #挂载ConfigMap到这个位置
readOnly: true
volumes:
- name: config
configMap:
name: configmap_name
注意:这种做法会使得 /etc/nginx/config.d目录下原所有文件都被隐藏掉
