在k8s中通常会有需要向容器传递变量参数,可以通过env或envFrom配置容器环境变量。
1. 先看看docker如何传参,假设docker启动参数如下:
1
|
docker run -e PARAMS="--spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai"
|
上述传递的参数名为:PARAMS
2.k8s通过env配置环境变量
1
2
3
4
5
6
7
8
|
spec:
template:
spec:
containers:
- name: xx-name
env:
- name: PARAMS
value: "--spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai"
|
3.k8s通过envFrom访问configMap配置环境变量
1
2
3
4
5
6
7
8
|
spec:
template:
spec:
containers:
- name: xx-name
envFrom:
- configMapRef:
name: xx-env-configmap
|
xx-env-configmap为对应的configMap,configMap配置如下:
1
2
3
4
5
6
|
apiVersion: v1
kind: ConfigMap
metadata:
name: xx-env-configmap
data:
PARAMS: --spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_xx?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai --server.servlet.context-path=/
|
上述配置一个key为PARAMS的参数变量,值以空格隔开,但不太直观,不太方便配置,可以采用以下这种形式:
1
2
3
4
5
6
7
8
|
apiVersion: v1
kind: ConfigMap
metadata:
name: xx-env-configmap
data:
PARAMS: >-
--spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_xx?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
--server.servlet.context-path=/
|
4.k8s通过env访问configMap配置环境变量
1
2
3
4
5
6
7
8
9
10
11
|
spec:
template:
spec:
containers:
- name: xx-name
env:
- name: PARAMS
valueFrom:
configMapKeyRef:
name: xx-env-configmap
key: PARAMS
|