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

ConfigMaps

A ConfigMap is a type of resource used to store the configurations required by applications. It is used to store configuration data or configuration files in key-value pairs.

A ConfigMap allows you to decouple configurations from your environments, so that your environments can use different configurations.

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 as an Environment Variable

ConfigMaps are usually referenced as environment variables and in volumes.

In the following example, property_1 of configmap-test is used as the value of the environment variable EXAMPLE_PROPERTY_1. After the container is started, it will reference the value of property_1 as the value of EXAMPLE_PROPERTY_1, that is, Hello.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    env:
    - name: EXAMPLE_PROPERTY_1
      valueFrom:
        configMapKeyRef:          # Reference the ConfigMap.
          name: configmap-test
          key: property_1
  imagePullSecrets:
  - name: default-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, the two files property_1 and property_2 are generated 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:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    volumeMounts:
    - name: vol-configmap           # Mount the volume named vol-configmap.
      mountPath: "/tmp"
  imagePullSecrets:
  - name: default-secret
  volumes:
  - name: vol-configmap
    configMap:                      # Reference the ConfigMap.
      name: configmap-test