生成容器內的環境變量
1.創建一個名字叫nginx-config的configmap, 變量名nginx_port的值是80, 變量名server_name的值是www.test.com
kubectl create configmap nginx-config --from-literal=nginx_port=80 --from-literal=server_name=www.test.com
2.驗證
kubectl get cm nginx-config -o yaml #其中data就是環境變量
kubectl describe cm nginx-config
3.創建一個pod, 引用上面定義的環境變量
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 1
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.11
ports:
- containerPort: 80
env:
- name: NGINX_SERVER_PORT #pod容器中的環境變量名字
valueFrom:
configMapKeyRef:
name: nginx-config #configmap的名字
key: nginx_port #configmap中定義的key
- name: NGINX_SERVER_NAME
valueFrom:
configMapKeyRef:
name: nginx-config
key: server_name
4.驗證
通過volumeMount使用ConfigMap
1.創建一個配置文件:
cat >www.conf <<EOF
server {
server_name www.test.com;
listen 80;
root /app/webroot/;
}
EOF
2.創建一個configmap, 文件內容作為value, 可以自定義key, 也可以使用文件名作為key
方式一: kubectl create configmap nginx-file --from-file=./www.conf
方式二:kubectl create configmap nginx-file --from-file=www.conf=./www.conf
3.創建一個deployment資源
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 1
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.11
ports:
- containerPort: 80
volumeMounts: #掛載
- name: nginxconfig #調用下面定義的存儲卷, 名字要一致
mountPath: /etc/nginx/conf.d/ #pod容器目錄
readOnly: true #只讀
volumes: #創建一個存儲卷
- name: nginxconfig #定義存儲卷名字
configMap: #定義存儲卷類型為configMap
name: nginx-file #引用名字叫nginx-file的configmap,
4.驗證
使用configmap限制條件
1.ConfigMap必須在Pod之前創建
2.ConfigMap受Namespace限制, 只有處於相同的NameSpace中的Pod才可以引用它