ConfigMap 与 Secret
约 659 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › K8s › 配置与存储(在新窗口打开) › ConfigMap 与 Secret
ConfigMap
ConfigMap 用于管理非敏感配置信息(环境变量、配置文件)。
创建 ConfigMap
# 从字面值创建
kubectl create configmap app-config --from-literal=APP_ENV=production --from-literal=LOG_LEVEL=info
# 从文件创建
kubectl create configmap app-config --from-file=app.properties
# 从目录创建
kubectl create configmap app-config --from-file=config/
# 从 .env 文件创建
kubectl create configmap app-env --from-env-file=.envapiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
APP_ENV: production
LOG_LEVEL: info
app.properties: |
db.host=localhost
db.port=3306使用 ConfigMap
apiVersion: v1
kind: Pod
metadata:
name: config-pod
spec:
containers:
- name: app
image: nginx:alpine
# 方式一:环境变量(部分配置)
env:
- name: APP_ENV
valueFrom:
configMapKeyRef:
name: app-config
key: APP_ENV
# 方式二:全部环境变量
envFrom:
- configMapRef:
name: app-config
# 方式三:Volume 挂载(完整配置文件)
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-configSecret
Secret 用于管理敏感数据(密码、API Token、SSH 密钥)。
创建 Secret
# 从字面值(自动 base64 编码)
kubectl create secret generic db-secret \
--from-literal=username=root \
--from-literal=password=secret123
# 从文件
kubectl create secret generic ssh-key --from-file=id_rsa
# TLS 证书
kubectl create secret tls my-tls --cert=server.crt --key=server.key
# Docker 仓库认证
kubectl create secret docker-registry registry-auth \
--docker-server=https://index.docker.io/v1/ \
--docker-username=myuser \
--docker-password=mypasswordapiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: cm9vdA== # base64("root")
password: c2VjcmV0MTIz # base64("secret123")使用 Secret
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
spec:
template:
spec:
containers:
- name: app
image: myapp:latest
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-secret
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
volumeMounts:
- name: ssh-key
mountPath: /root/.ssh
readOnly: true
volumes:
- name: ssh-key
secret:
secretName: ssh-key
# 从私有仓库拉取镜像
imagePullSecrets:
- name: registry-authConfigMap vs Secret
| 对比 | ConfigMap | Secret |
|---|---|---|
| 数据存储 | 明文 | base64 编码(非加密) |
| 用途 | 配置文件、环境变量 | 密码、Token、证书 |
| 自动加密 | 否 | 可使用 kubectl encrypt 或外部 Secret 存储 |
| Volume 更新 | 自动同步(几分钟内) | 自动同步 |
| 大小限制 | 1MB(etcd 限制) | 1MB |
热更新
Volume 挂载的 ConfigMap/Secret 更新后,Pod 内文件会自动同步(数分钟内):
# 更新 ConfigMap
kubectl edit configmap app-config
# Pod 内挂载的文件会自动更新(但环境变量不会)
# 环境变量方式需要重启 Pod
kubectl rollout restart deployment myapp小结
- ConfigMap 存非敏感配置,Secret 存敏感数据(base64 编码)。
- 两种使用方式:环境变量(适合少量配置)和 Volume 挂载(适合完整配置文件)。
- Secret 的 base64 不是加密,生产环境应使用外部 Secret 存储(如 HashiCorp Vault、AWS Secrets Manager)。
- Volume 挂载的 ConfigMap/Secret 可热更新,环境变量方式需重启 Pod。
- YAML 中直接写 data 时用
stringData可避免手动 base64 编码。
上一节:NetworkPolicy 下一节:Volume 与 PV/PVC
