
在 Kubernetes 中,ConfigMap
和 Secret
是用于管理配置数据和敏感信息的两种资源。ConfigMap
用于存储非机密数据,Secret
用于存储敏感数据,如密码、OAuth 令牌等。以下是详细介绍和示例。
ConfigMap
用于存储非机密的键值对配置数据,这些数据可以在 Pod 中使用。
--dry-run=client,本地构建资源对象,不连接 API Server(推荐用于生成 YAML)。
--dry-run=server,把资源对象发送到 API Server 做一次“校验”,但不真的创建资源(必须能访问集群)。
不加 --dry-run,不会创建 ConfigMap 到集群中。
kubectl create configmap my-config --from-literal=key=value --dry-run=client -o yaml
你可以通过 YAML 文件创建一个 ConfigMap
。
apiVersion: v1
kind: ConfigMap
metadata:
name: example-config
data:
# 配置数据以键值对的形式存在
database_url: "mongodb://db.example.com:27017"
feature_flag: "true"
应用此配置:
kubectl apply -f configmap.yaml
在 Pod 中使用 ConfigMap
有两种常见的方法:作为环境变量或挂载为文件。
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: myapp:latest
env:
- name: DATABASE_URL
valueFrom:
configMapKeyRef:
name: example-config
key: database_url
- name: FEATURE_FLAG
valueFrom:
configMapKeyRef:
name: example-config
key: feature_flag
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: myapp:latest
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: example-config
Secret
用于存储敏感信息,例如密码、密钥、令牌等。这些数据在存储和传输过程中都会进行编码。
你可以通过 YAML 文件创建一个 Secret
,数据需要进行 Base64 编码。
apiVersion: v1
kind: Secret
metadata:
name: example-secret
type: Opaque
data:
# 数据需要进行 Base64 编码
password: cGFzc3dvcmQ=
api-key: YXBpa2V5
或者通过命令直接创建:
kubectl create secret generic example-secret --from-literal=password=my-password --from-literal=api-key=my-api-key
在 Pod 中使用 Secret
也有两种常见的方法:作为环境变量或挂载为文件。
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: myapp:latest
env:
- name: PASSWORD
valueFrom:
secretKeyRef:
name: example-secret
key: password
- name: API_KEY
valueFrom:
secretKeyRef:
name: example-secret
key: api-key
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
containers:
- name: example-container
image: myapp:latest
volumeMounts:
- name: secret-volume
mountPath: /etc/secret
volumes:
- name: secret-volume
secret:
secretName: example-secret
这两种资源帮助将配置与代码分离,提升了应用的灵活性和安全性。