CKAD_Configuring a Pod to Use a ConfigMap
Configuring a Pod to Use a ConfigMap
3 min readJun 27, 2023
- Create a new file named
config.txt
with the following environment variables as key/value pairs on each line.
DB_URL
equates tolocalhost:3306
DB_USERNAME
equates topostgres
- Create a new ConfigMap named
db-config
from that file. - Create a Pod named
backend
that uses the environment variables from the ConfigMap and runs the container with the imagenginx
. - Shell into the Pod and print out the created environment variables. You should find
DB_URL
andDB_USERNAME
with their appropriate values.
1.Create a new file named
config.txt
with the following environment variables as key/value pairs on each line.
可使用echo
echo -e "DB_URL=localhost:3306\nDB_USERNAME=postgres" > config.txt
-e為 使得 echo
命令將 \n
解釋為換行符
或是 printf
printf "DB_URL=localhost:3306\nDB_USERNAME=postgres\n" > config.txt
2.Create a new ConfigMap named
db-config
from that file.
使用 create configmap
kubectl create configmap db-config --from-file=config.txt
3.Create a Pod named
backend
that uses the environment variables from the ConfigMap and runs the container with the imagenginx
.
kubectl run backend --image=nginx --restart=Never -o yaml --dry-run=client > pod.yaml
kubectl run backend
: 使用kubectl run
命令創建一個名為 "backend" 的新 Pod。--image=nginx
: 指定 Pod 使用 "nginx" 鏡像。--restart=Never
: 設置 Pod 的重啟策略為 "Never",即當 Pod 終止後不會自動重新啟動。-o yaml
: 指定將生成的 Pod 配置以 YAML 格式輸出。--dry-run=client
: 使用--dry-run=client
選項進行模擬操作,不會對實際的集群進行任何更改。> pod.yaml
: 將輸出的 YAML 配置重定向到名為 "pod.yaml" 的文件中,而不是輸出到終端。
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: backend
name: backend
spec:
containers:
- image: nginx
name: backend
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
產生的yaml
增加
envFrom:
— configMapRef:
name: db-config
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: backend
name: backend
spec:
containers:
- image: nginx
name: backend
envFrom:
- configMapRef:
name: db-config
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Never
status: {}
Create the Pod by pointing the
create
command to the YAML file.
$ kubectl create -f pod.yaml
Log into the Pod and run the env
command.
kubectl exec backend -it -- /bin/sh
進入pod內輸入env 查詢環境變數
可以找到DB_URL 跟 DB_USERNAME