简介
ConfigMap 是一种 API 对象,用来将非机密性的数据保存到键值对中。使用时, Pods 可以将其用作环境变量、命令行参数或者存储卷中的配置文件。
ConfigMap 将你的环境配置信息和 容器镜像 解耦,便于应用配置的修改。
创建ConfigMap
你可以写一个引用 ConfigMap 的 Pod 的 spec
,并根据 ConfigMap 中的数据在该 Pod 中配置容器。这个 Pod 和 ConfigMap 必须要在同一个 名字空间 中。
这是一个 ConfigMap 的示例,它的一些键只有一个值,其他键的值看起来像是 配置的片段格式。
apiVersion: v1
kind: ConfigMap
metadata:
name: game-demo
data:
# property-like keys; each key maps to a simple value
player_initial_lives: "3"
ui_properties_file_name: "user-interface.properties"
# file-like keys
game.properties: |
enemy.types=aliens,monsters
player.maximum-lives=5
user-interface.properties: |
color.good=purple
color.bad=yellow
allow.textmode=true
利用kubectl命令创建configmap后。你可以在kubernetes dashboard里查看
Configmap的使用
1. 容器的环境变量
env:
# 定义环境变量
- name: PLAYER_INITIAL_LIVES # 请注意这里和 ConfigMap 中的键名是不一样的
valueFrom:
configMapKeyRef:
name: game-demo # 这个值来自 ConfigMap
key: player_initial_lives # 需要取值的键
- name: UI_PROPERTIES_FILE_NAME
valueFrom:
configMapKeyRef:
name: game-demo
key: ui_properties_file_name
2. 文件挂在的方式
volumeMounts:
- name: config
mountPath: "/config"
readOnly: true
volumes:
# 你可以在 Pod 级别设置卷,然后将其挂载到 Pod 内的容器中
- name: config
configMap:
# 提供你想要挂载的 ConfigMap 的名字
name: game-demo
# 来自 ConfigMap 的一组键,将被创建为文件
items:
- key: "game.properties"
path: "game.properties"
- key: "user-interface.properties"
path: "user-interface.properties"
完整yaml文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: test123
labels:
app: test123
spec:
replicas: 1
template:
metadata:
name: test123
labels:
app: test123
spec:
containers:
- name: test123
image: test-demo1:v1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
env:
# Define the environment variable
- name: PLAYER_INITIAL_LIVES # Notice that the case is different here
# from the key name in the ConfigMap.
valueFrom:
configMapKeyRef:
name: game-demo # The ConfigMap this value comes from.
key: player_initial_lives # The key to fetch.
- name: UI_PROPERTIES_FILE_NAME
valueFrom:
configMapKeyRef:
name: game-demo
key: ui_properties_file_name
volumeMounts:
- name: config
mountPath: "/config"
readOnly: true
volumes:
# You set volumes at the Pod level, then mount them into containers inside that Pod
- name: config
configMap:
# Provide the name of the ConfigMap you want to mount.
name: game-demo
# An array of keys from the ConfigMap to create as files
items:
- key: "game.properties"
path: "game.properties"
- key: "user-interface.properties"
path: "user-interface.properties"
selector:
matchLabels:
app: test123
---
apiVersion: v1
kind: Service
metadata:
name: test123-service
labels:
app: test123-service
spec:
selector:
app: test123
ports:
- port: 8087
targetPort: 8089
nodePort: 30082
type: NodePort
验证
进入pod里查看config的目录和查看环境变量
root@test123-cf887dd59-6l74b:/config# ls
game.properties user-interface.properties
root@test123-cf887dd59-6l74b:/config# cat game.properties
enemy.types=aliens,monsters
player.maximum-lives=5
root@test123-cf887dd59-6l74b:/config# echo $PLAYER_INITIAL_LIVES
3
参考资料