假如现在有demo.sh和Dockerfile
demo.sh:
#!/bin/bash
while [[ true ]]; do
echo time $INTERVAL
sleep $INTERVAL
done
Dockerfile:
FROM centos
ADD demo.sh /root/demo.sh
ENTRYPOINT [ "/root/demo.sh" ]
构建镜像
docker build -t demo:env .
创建pod
apiVersion: v1
kind: Pod
metadata:
name: mydemo01
namespace: test01
labels:
app: mydemo01
spec:
containers:
- name: mydemo01
image: demo:env
env:
- name: INTERVAL # 环境变量名称
value: "1" # 指定环境变量值
restartPolicy: Always
如果docker容器中的应用是java编写,使用System.getenv[“INTERVAL”]来获取环境变量,如果是python编写的,使用os.environ[‘INTERVAL’],根据不同应用环境相应获取系统环境变量即可。
创建一个配置条目
[root@master test01]# kubectl create configmap mydemo-conf --from-literal=sleep-interval=2 -n test01
[root@master test01]# kubectl get configmaps -n test01
NAME DATA AGE
mydemo-conf 1 17s
[root@master test01]# kubectl describe configmaps -n test01 mydemo-conf
Name: mydemo-conf
Namespace: test01
Labels: <none>
Annotations: <none>
Data
====
sleep-interval:
----
2
创建pod
apiVersion: v1
kind: Pod
metadata:
name: mydemo01
namespace: test01
labels:
app: mydemo01
spec:
containers:
- name: mydemo01
image: demo:env
env:
- name: INTERVAL # 变量名称
valueFrom: # 值来源于configMap
configMapKeyRef:
name: mydemo-conf # 指定configMap名称
key: sleep-interval # 指定配置条目名称
restartPolicy: Always
demo.sh
#!/bin/bash
while [[ true ]]; do
echo args1: $HOST,args2: $PORT,args3: $DB_NAME
sleep $INTERVAL
done
Dockerfile
FROM centos
ADD demo.sh /root/demo.sh
ENTRYPOINT [ "/root/demo.sh" ]
生成镜像
docker build -t demo:env .
创建configMap
[root@master test01]# kubectl create configmap mydemo-conf -n test01 --from-literal=HOST=127.0.0.1 --from-literal=PORT=3306 --from-literal=DB_NAME=users --from-literal=INTERVAL=2
[root@master test01]# kubectl describe configmaps -n test01 mydemo-conf
Name: mydemo-conf
Namespace: test01
Labels: <none>
Annotations: <none>
Data
====
PORT:
----
3306
DB_NAME:
----
users
HOST:
----
127.0.0.1
INTERVAL:
----
2
创建pod
apiVersion: v1
kind: Pod
metadata:
name: mydemo01
namespace: test01
labels:
app: mydemo01
spec:
containers:
- name: mydemo01
image: demo:env
envFrom:
- configMapRef:
name: mydemo-conf
imagePullPolicy:
restartPolicy: Always
验证
[root@master test01]# kubectl get pods -n test01
NAME READY STATUS RESTARTS AGE
mydemo01 1/1 Running 0 21s
[root@master test01]# kubectl logs -f -n test01 mydemo01
args1: 127.0.0.1,args2: 3306,args3: users
args1: 127.0.0.1,args2: 3306,args3: users
args1: 127.0.0.1,args2: 3306,args3: users