ConfigMap

一、ConfigMap

在 Kubernetes 中,ConfigMap 是一种用于管理配置数据的资源对象。它的主要作用是将配置数据从容器镜像中分离出来,使得配置可以在不重新构建镜像的情况下进行修改和管理。ConfigMap 允许将配置信息以键值对的形式存储,并可以在 Pods 中作为环境变量、命令行参数或者文件的形式提供给应用程序。

实际例子

1.假设有一个应用程序,它需要读取数据库的连接配置。可以使用 ConfigMap 来管理这些配置。

1.创建 ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: db-config
data:
  DB_HOST: "localhost"
  DB_PORT: "5432"
  DB_USER: "admin"
  DB_PASSWORD: "password123"

kubectl apply -f configmap.yaml
2.在 Pod 中使用 ConfigMap
apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: my-app-container
    image: my-app-image
    env:
    - name: DB_HOST
      valueFrom:
        configMapKeyRef:
          name: db-config
          key: DB_HOST
    - name: DB_PORT
      valueFrom:
        configMapKeyRef:
          name: db-config
          key: DB_PORT
    - name: DB_USER
      valueFrom:
        configMapKeyRef:
          name: db-config
          key: DB_USER
    - name: DB_PASSWORD
      valueFrom:
        configMapKeyRef:
          name: db-config
          key: DB_PASSWORD
3.验证ConfigMap
kubectl get configmap db-config -o yaml
kubectl describe pod my-app

2.configmap挂载为文件,应用程序从配置文件中读取数据库连接信息。

1.创建 ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  config.properties: |
    db.host=localhost
    db.port=5432
2.在 Pod 中使用 ConfigMap
apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: my-app-container
    image: my-app-image
    volumeMounts:
    - name: config-volume
      mountPath: /etc/config
  volumes:
  - name: config-volume
    configMap:
      name: app-config

ConfigMap 中的 config.properties 文件将被挂载到容器的 /etc/config 目录,应用程序可以读取这个文件来获取配置信息。

实验1:挂载nginx配置和主站点网页文件,运行nginx pod容器,通过service去访问nginx web服务

1.configmap的yaml文件
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-server-config
  namespace: default
data:
  default.conf: |
    server {
      listen 80;
      server_name cc2024.com;

      location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
      }

    }
  index.html:
    helloworld
2.pod的yaml文件
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: default
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: harbor.hiuiu.com/nginx/nginx:1.21.5
    volumeMounts:
    - name: nginx-config-volume
      mountPath: /etc/nginx/conf.d/default.conf
      subPath: default.conf
    - name: nginx-config-volume
      mountPath: /usr/share/nginx/html/index.html
      subPath: index.html
  volumes:
  - name: nginx-config-volume
    configMap:
      name: nginx-server-config

---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: default
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80        # Service 的端口
      targetPort: 80  # Pod 的端口,假设 NGINX 在容器内部监听 80 端口
      nodePort: 30000 # NodePort 的端口,可以选择在 30000-32767 范围内的值,或者让Kubernetes 自动分配

你可能感兴趣的:(容器,kubernetes,k8s)