配置信息注入 configmap、secret
简介
ConfigMap API资源提供了将配置数据注入容器的方式,同时保证该机制对容器来说是透明的。ConfigMap可以被用来保存单个属性,也可以用来保存整个配置文件或者JSON二进制大对象。
ConfigMap API资源存储键/值对配置数据,这些数据可以在pods里使用。ConfigMap跟Secrets类似,但是ConfigMap可以更方便的处理不包含敏感信息的字符串。
创建 configmap
通过命令行创建
kubectl create cm nginx-config --from-literal=nginx_port=80 --from-literal=server_name=myapp.test.org
kubectl create configmap nginx-www --from-file=./www.conf
# cat www.conf
server {
server_name myapp.test.org;
listen 80;
root /data/web/html;
}
查看 configmap
# kubectl get cm
NAME DATA AGE
nginx-config 2 29m
nginx-www 1 37m
实例一
# cat pod-configmap.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-cm-1
namespace: default
labels:
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
ports:
- name: http
containerPort: 80
env:
- name: NGINX_SERVER_PORT
valueFrom:
configMapKeyRef:
name: nginx-config
key: nginx_port
- name: NGINX_SERVER_NAME
valueFrom:
configMapKeyRef:
name: nginx-config
key: server_name
实例二
挂载方式,通过 kubectl edit cm nginx-config 进行编辑后,pod 里面的变量也会进行更新
# cat pod-configmap2.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-cm-2
namespace: default
labels:
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
ports:
- name: http
containerPort: 80
volumeMounts:
- name: nginxconf
mountPath: /etc/nginx/config.d/
readOnly: true
volumes:
- name: nginxconf
configMap:
name: nginx-config
实例三
通过 kubectl edit cm nginx-www 进行编辑后,pod 里面的配置文件也会进行更新,但是监听端口不会更新,需要重载
# cat pod-configmap3.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-cm-3
namespace: default
labels:
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
ports:
- name: http
containerPort: 80
volumeMounts:
- name: nginxconf
mountPath: /etc/nginx/conf.d/
readOnly: true
volumes:
- name: nginxconf
configMap:
name: nginx-www
创建 secret
# 支持三种方式:docker-registry、generic、tls
# kubectl create secret generic mysql-root-password --from-literal=password=123456
# kubectl get secrets mysql-root-password
NAME TYPE DATA AGE
mysql-root-password Opaque 1 15s
# kubectl get secrets mysql-root-password -o yaml
apiVersion: v1
data:
password: MTIzNDU2
kind: Secret
metadata:
creationTimestamp: "2018-12-18T03:29:02Z"
name: mysql-root-password
namespace: default
resourceVersion: "1518882"
selfLink: /api/v1/namespaces/default/secrets/mysql-root-password
uid: 10721e2e-0275-11e9-928f-005056bae900
type: Opaque
# echo MTIzNDU2 | base64 -d # 这种并不是真正的加密
123456
实例
# cat pod-secret-1.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-secret-1
namespace: default
labels:
app: myapp
tier: frontend
spec:
containers:
- name: myapp
image: ikubernetes/myapp:v1
ports:
- name: http
containerPort: 80
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-root-password
key: password
# kubectl exec -it pod-secret-1 -- printenv | grep MYSQL_ROOT_PASSWORD
MYSQL_ROOT_PASSWORD=123456
当 ConfigMap 以数据卷的形式挂载进Pod的时,这时更 新ConfigMap(或删掉重建ConfigMap),Pod内挂载的配置信息会热更新。这时可以增加一些监测配置文件变更的脚本,然后reload对应服务。