kubernetes之configmap

生成容器内的环境变量

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才可以引用它 

猜你喜欢

转载自www.cnblogs.com/lovelinux199075/p/11294987.html