Updated on 2024-11-01 GMT+08:00

ConfigMap

A ConfigMap is a resource object for storing configuration information required by applications. It uses the key-value pair to save configuration data. It can be used to save a single attribute or configuration file.

A ConfigMap can be used to decouple configuration and make different configurations in different environments. Compared with the environment variables, the ConfigMap referenced in the pod can be updated in real time. After the ConfigMap data is updated, the ConfigMap referenced in the pod is updated synchronously.

Creating a ConfigMap

In the following example, a ConfigMap named configmap-test is created. The ConfigMap configuration data is defined in the data field.

apiVersion: v1
kind: ConfigMap
metadata:
  name: configmap-test
data:                    # Configuration data
  property_1: Hello
  property_2: World

Referencing a ConfigMap in Environment Variables

A ConfigMap is usually referenced in environment variables and volumes.

In the following example, the property_1 of configmap-test is used as the value of the environment variable EXAMPLE_PROPERTY_1. In this case, the value of EXAMPLE_PROPERTY_1 is the value of property_1 after the container is started, that is, Hello.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:latest
    name: container-0
    resources:
      limits:
        cpu: 500m
        memory: 1024Mi
      requests:
        cpu: 500m
        memory: 1024Mi
    env:
    - name: EXAMPLE_PROPERTY_1
      valueFrom:
         configMapKeyRef:         # Reference the ConfigMap.
          name: configmap-test
          key: property_1
  imagePullSecrets:
  - name: imagepull-secret

Referencing a ConfigMap in a Volume

Referencing a ConfigMap in a volume is to fill its data in configuration files in the volume. Each piece of data is saved in a file. The key is the file name, and the key value is the file content.

In the following example, create a volume named vol-configmap, reference the ConfigMap named configmap-test in the volume, and mount the volume to the /tmp directory of the container. After the pod is created, there are two files property_1 and property_2 in the /tmp directory of the container, and the values are Hello and World.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:latest
    name: container-0
    resources:
      limits:
        cpu: 500m
        memory: 1024Mi
      requests:
        cpu: 500m
        memory: 1024Mi
    volumeMounts:
    - name: vol-configmap           # Mount the volume named vol-configmap.
      mountPath: "/tmp1"
  imagePullSecrets:
  - name: imagepull-secret
  volumes:
  - name: vol-configmap
    configMap:                      # Reference the ConfigMap.
      name: configmap-test