k8s 中为 Pod 部署环境变量从配置文件

创建ConfigMap

配置信息

如配置 MySQL 连接信息

文件名称: db-config.yaml

1
2
3
4
5
6
7
8
9
10
11
12
kind: ConfigMap
apiVersion: v1
metadata:
name: db-config
namespace: default
data:
DB_HOST: 127.0.0.1
DB_NAME: test
DB_PASS: test
DB_PORT: '5432'
DB_USER: test

部署配置

使用 kubectl 进行部署

1
kubectl apply -f db-config.yaml

容器引用配置

Pod容器默认读取环境变量,通过名称

字段 说明
id-gen 服务名称
docker.io/id-service:latest 测试镜像
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
kind: Deployment
apiVersion: apps/v1
metadata:
name: id-gen
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: id-gen
template:
metadata:
creationTimestamp: null
labels:
app: id-gen
spec:
containers:
- name: container-jvnzzs
image: 'docker.io/id-service:latest'
envFrom:
- configMapRef:
name: db-config
imagePullPolicy: IfNotPresent
restartPolicy: Always
terminationGracePeriodSeconds: 30

关键配置

1
2
3
envFrom:
- configMapRef:
name: db-config