Location>code7788 >text

K8s Newbie Series ConfigMap Resources

Popularity:962 ℃/2025-05-04 12:12:42

Overview

In Kubernetes (K8s), ConfigMap is an API object that saves non-confidential data into key-value pairs. Pods can be used as environment variables, command line parameters, or configuration files in storage volumes.

ConfigMap allows you to separate configuration manifests from mirrored content to maintain portability of containerized applications. For example, you can download and run the same container image to start the container for local development, system testing, or run real-time end-user workloads.

ConfigMap is an API object that allows you to store the configurations that other objects need to use. Unlike other Kubernetes objects, ConfigMap uses data and binaryData fields. These fields can receive key-value pairs as their values. Both data and binaryData fields are optional. The data field is designed to hold UTF-8 strings, while binaryData is designed to hold binary data as base64-encoded strings.

Official document address:/zh-cn/docs/tasks/configure-pod-container/configure-pod-configmap/

The role of ConfigMap

Centrally store configuration information:

  • ConfigMap can store application configuration information (such as database connection strings, log levels, service ports, etc.) in one place. These configuration information exists in the form of key-value pairs, which is convenient for management and maintenance. For example, an application needs to connect to a database, and its database username, password, address and other information can be stored in ConfigMap.

  • With ConfigMap, developers can separate configuration information from application code, making applications more general and portable. When you need to run an application in different environments (such as development environment, test environment, and production environment), you only need to modify the configuration values ​​in ConfigMap without modifying the application code.
    Supports multiple data formats

  • ConfigMap supports a variety of data formats, including strings, file contents, etc. You can directly store the contents of configuration files (such as properties files, yaml files, etc.) into ConfigMap. For example, an application's configuration file contains multiple configuration items, which can be read and stored in a ConfigMap, and the application then reads these configuration items through a ConfigMap.

Injection configuration

ConfigMap can inject configuration information into a container, which can access these configuration information through environment variables, mount volumes, etc.

  • Environment variable method: You can inject configuration items in ConfigMap into the container as environment variables. For example, a container needs to access a database, and its database username and password can be injected into the container in the form of environment variables through ConfigMap, which can directly use these environment variables to obtain configuration information at runtime.

  • Mounting volume method: You can mount configuration files in ConfigMap to the container's file system. For example, an application needs to read a configuration file, and can mount the ConfigMap that stores the contents of the configuration file to a directory in the container, which can be accessed through the file path when running.

Dynamically update configuration

When the configuration information in ConfigMap changes, the container can sense these changes and reload the configuration information as needed. This ability to dynamically update configurations allows applications to quickly respond to configuration changes without restarting the container. For example, when the connection address of the database changes, update the corresponding configuration item in ConfigMap, and the container can automatically acquire the new configuration and re-establish the database connection.

Improve code maintainability

Store configuration information in ConfigMap to make application code more concise and clear. Developers do not need to hardcode configuration information in the code, reducing the complexity and coupling of the code. When you need to modify the configuration, you only need to modify the ConfigMap without modifying the code, reducing maintenance costs.

Enhance the portability of code

Because the configuration information is separated from the code, the application can run in different environments without modifying the code. By adjusting the configuration values ​​in ConfigMap, it is easy to migrate applications from development environments to test environments or production environments, improving application portability.

Multi-container shared configuration

In Kubernetes, a ConfigMap can be shared by multiple containers. When multiple containers need to use the same configuration information, the same ConfigMap can be used to avoid the problem of duplicate configuration. For example, in a microservice architecture, multiple service instances may need to access the same database, and the configuration information of the database can be stored in a ConfigMap, through which all service instances can obtain configuration information.

Multi-application shared configuration

Different applications can also share the same ConfigMap. For example, multiple applications may need to access the same external service, and the configuration information of the external service can be stored in a ConfigMap, through which all applications can obtain the configuration information.

Simplify the deployment process

When deploying applications, ConfigMap can quickly pass configuration information to containers. Developers only need to define the ConfigMap and associate the ConfigMap with the container during deployment to complete the configuration injection, simplifying the deployment process.

Convenient operation and maintenance management

Operations and maintenance personnel can centrally manage configuration information through ConfigMap, which facilitates configuration modification, backup and restore. When problems occur, you can quickly locate the cause of the problem by viewing the configuration information in ConfigMap, which improves operation and maintenance efficiency.

Create a ConfigMap

Create ComfigMap with files

grammar:

kubectl create configmap [name of config] --from-file=[file] ... --from-file=[file]

 # Or by
 kubectl create configmap [name of config] --from-env-file=[file] ... --from-env-file=[file]

 Analysis:
 --from-env-file: The ConfigMap can be created through env, for example, name=zhangsan. When created with --from-file, its configuration items will not change.
 However, when created through --from-env-file, it will automatically resolve to the form of name: zhangsan

Which files can be used to create a ConfigMap?

  • .properties file: This is a commonly used configuration file type in Java applications. It uses the format of key-value pairs to store configuration information, such as:
=localhost
=3306
  • .yaml/.yml file: is a highly readable data serialization format, widely used in Kubernetes' own configuration and many application configurations, such as:
database:
  host: localhost
  port: 3306
server:
  port: 8080
  • .ini file: It is often used to store configuration data. Its structure contains multiple sections. Each section has multiple key-value pairs. The example is as follows:
[database]
host=localhost
port=3306

[server]
port=8080
  • .json file: A lightweight data exchange format, commonly used to store structured data, the examples are as follows:
{
  "database": {
    "host": "localhost",
    "port": 3306
  },
  "server": {
    "port": 8080
  }
}
  • .conf file: Usually it is the configuration file of various services. The configuration files of services such as Nginx and Apache are often based on the extension.
worker_processes auto;
error_log /var/log/nginx/ warn;
pid /var/run/;
events {
    worker_connections 1024;
}
http {
    server {
    }
}
  • .txt file: a normal text file that can store any text information, such as storing log levels, application descriptions, etc.
asdsxfaseqwesd

Create a ConfigMap through properties file

Example:

# Create properties file
 [root@master01 ~/configmap]# cat
 =jdbc:mysql://localhost:3306/mydb
 =root
 =password

 # Create a ComfigMap
 [root@master01 ~/configmap]# kubectl create configmap db-config --from-file=
 configmap/db-config created

 # View ConfigMap
 [root@master01 ~/configmap]# kubectl get configmap
 NAME DATA AGE
 db-config 1 53s

 # View the yaml file generated by ConfigMap
 [root@master01 ~/configmap]# kubectl get configmap db-config -o yaml
 apiVersion: v1
 metadata:
   creationTimestamp: "2025-05-02T06:02:42Z"
   name: db-config
   namespace: default
   resourceVersion: "59760"
   uid: dc9de3eb-5e19-47fd-854d-2c4fcddbf8ba
 data:
   : |
     =jdbc:mysql://localhost:3306/mydb
     =root
     =password
 kind: ConfigMap

 # View ConfigMap details
 [root@master01 ~/configmap]# kubectl describe configmap db-config
 Name: db-config
 Namespace: default
 Labels: <none>
 Annotations: <none>

 Data #This is the corresponding data information
 ====
 :
 ----
 =jdbc:mysql://localhost:3306/mydb
 =root
 =password


 BinaryData #Here is binary data
 ====

 Events: <none>

Create a ConfigMap from a directory

grammar:

kubectl create configmap [name of config] --from-file=[filepath] ... --from-file=[filepath]

 # Or by
 kubectl create configmap [name of config] --from-env-file=[filepath] ... --from-env-file=[filepath]

 Analysis:
 --from-env-file: The ConfigMap can be created through env, for example, name=zhangsan. When created with --from-file, its configuration items will not change.
 However, when created through --from-env-file, it will automatically resolve to the form of name: zhangsan

This method is actually the same as creating a ConfigMap through a file.

Example:

# Create a directory
 [root@master01 ~]# mkdir -p /root/configmap/app

 # Create data
 [root@master01 ~]# wget /examples/configmap/ -O /root/configmap/app/
 #...Omit some information
 /root/configmap/app/                 100%[==================================================================================================================>]     157  -.KB/s    in 0s

 2025-05-02 14:09:46 (178 MB/s) - '/root/configmap/app/’ saved [157/157]
 [root@master01 ~]# wget /examples/configmap/ -O /root/configmap/app/
 #...Omit some information
 /root/configmap/app/                   100%[==================================================================================================================>]      83  -.KB/s    in 0s

 2025-05-02 14:10:03 (156 MB/s) - '/root/configmap/app/’ saved [83/83]

 # Create a ConfigMap
 [root@master01 ~]# kubectl create configmap app-config --from-file=/root/configmap/app
 configmap/app-config created

 # Check ConfigMap, two files become one configMap
 [root@master01 ~]# kubectl get configmap app-config -o yaml
 apiVersion: v1
 kind: ConfigMap
 metadata:
   creationTimestamp: "2025-05-02T06:13:01Z"
   name: app-config
   namespace: default
   resourceVersion: "61185"
   uid: 2cce2598-db6f-41a2-89fe-f144fac4159c
 data:
   : |-
     Enemies=aliens
     lives=3
     =true
     =noGoodRotten
     =UUDDLRLRBABAS
     =true
     =30
   : |
     =purple
     =yellow
     =true
     =fairlyNice

Create a ConfigMap with literals

ConfigMap also supports direct input of literals to create

grammar:

kubectl create configmap [configName] [--from-literal="key=value"] ... [--from-literal="key=value"]

Example:

# Create a ConfigMap
 [root@master01 ~]# kubectl create configmap user-config --from-literal="=zhangsan" \
                                       --from-literal="=18" \
                                       --from-literal="=beijing"
 configmap/user-config created

 # View ConfigMap's yaml file
 [root@master01 ~]# kubectl get configmap user-config -o yaml
 apiVersion: v1
 kind: ConfigMap
 metadata:
   creationTimestamp: "2025-05-02T06:35:22Z"
   name: user-config
   namespace: default
   resourceVersion: "64263"
   uid: 9ffe4dc3-31ee-4cde-bbfe-24041aa824bd
 data:
   : beijing
   : "18"
   : zhangsan

 # View details
 [root@master01 ~]# kubectl describe configmap user-config
 Name: user-config
 Namespace: default
 Labels: <none>
 Annotations: <none>

 Data
 ====
 :
 ----
 18
 :
 ----
 zhangsan
 :
 ----
 beijing

 BinaryData
 ====

 Events: <none>

Create a ConfigMap from a resource inventory

ConfigMap can also be created through K8s Yaml files. There are two ways to create ConfigMap through resource lists. One is the class attribute key and the other is the class file key.

Example:

# Define resource list
 [root@master01 ~/configmap]# cat
 apiVersion: v1
 kind: ConfigMap
 metadata:
   name: game-demo
 data:
   # class attribute key; each key is mapped to a simple value
   player_initial_lives: "3"
   ui_properties_file_name: ""

   # File key
   : |
     =aliens,monsters
     -lives=5
   : |
         server {
             listen:80;
             server_name:xxx;
             root:/root;
             location:{
                 xxx
             }
         }

 # Create a configMap
 [root@master01 ~/configmap]# kubectl apply -f
 configmap/game-demo created

 # View yaml file
 [root@master01 ~/configmap]# kubectl get configmap game-demo -o yaml
 apiVersion: v1
 kind: ConfigMap
 metadata:
   annotations:
     /last-applied-configuration: |
       {"apiVersion":"v1","data":{"":"=aliens,monsters\-lives=5\n","":"server {\n listen:80;\n server_name:xxx;\n root:/root;\n location:{\n xxx\n }\n}\n","player_initial_lives":"3","ui_properties_file_name":""},"kind":"ConfigMap","metadata":{"annotations":{},"name":"game-demo","namespace":"default"}}
   creationTimestamp: "2025-05-02T06:48:39Z"
   name: game-demo
   namespace: default
   resourceVersion: "66094"
   uid: d2f71bfb-5a8d-4cd4-b9fc-b490aef77f67
 data:
   : |
     =aliens,monsters
     -lives=5
   : |
     server {
         listen:80;
         server_name:xxx;
         root:/root;
         location:{
             xxx
         }
     }
   player_initial_lives: "3"
   ui_properties_file_name:

 # View details
 [root@master01 ~/configmap]# kubectl describe cm game-demo
 Name: game-demo
 Namespace: default
 Labels: <none>
 Annotations: <none>

 Data
 ====
 :
 ----
 server {
     listen:80;
     server_name:xxx;
     root:/root;
     location:{
         xxx
     }
 }

 player_initial_lives:
 ----
 3
 ui_properties_file_name:
 ----

 :
 ----
 =aliens,monsters
 -lives=5


 BinaryData
 ====

 Events: <none>

Modify the value of ConfigMap

ConfigMap cannot modify the name, but its value can be modified

passkubectlMethod modification

Can be passedkubectl edit configmap configmapnameTo modify its value, after using the kubectl command, a similarvimEditing interface, use it after modification:wqAfter saving

Modify through file

After modifying the resource file, the same key in configmap will be overwritten, and different keys will be added, and no unnecessary keys will be deleted.

View ConfigMap

# View all ConfigMaps
 [root@master01 ~]# kubectl get configmap -A
 NAMESPACE NAME DATA AGE
 calico-apiserver 1 6d6h
 calico-system active-operator 1 6d6h
 calico-system cni-config 1 6d6h
 calico-system 1 6d6h
 calico-system tigera-ca-bundle 2 6d6h
 default app-config 2 4h39m
 default db-config 1 6h13m
 default env-config 3 5h17m

 # View ConfigMap in the specified namespace
 [root@master01 ~]# kubectl get configmap -n calico-system
 NAME DATA AGE
 active-operator 1 6d6h
 cni-config 1 6d6h
    1 6d6h
 tigera-ca-bundle 2 6d6h

 # View as yaml file
 [root@master01 ~]# kubectl get configmap db-config -o yaml
 apiVersion: v1
 kind: ConfigMap
 metadata:
   creationTimestamp: "2025-05-02T06:02:42Z"
   name: db-config
   namespace: default
   resourceVersion: "59760"
   uid: dc9de3eb-5e19-47fd-854d-2c4fcddbf8ba
 data:
   : |
     =jdbc:mysql://localhost:3306/mydb
     =root
     =password

Delete ConfigMap

usekubectl delete configmap [name1 name2 ... nameN]Just delete it in the way
Example:

[root@master01 ~]# kubectl delete configmap db-config
 configmap "db-config" deleted
 # Verify that the deletion is successful
 [root@master01 ~]# kubectl get configmap db-config
 Error from server (NotFound): configmaps "db-config" not found

ConfigMap for Pod

There are two ways to use the ConfigMap resource, one is to use it through environment variables, and the other is to use it through data volume mount.

Notice:

  • Static Pods cannot use ConfigMap
  • Pod and ConfigMap must be in the same namespace.

Pod uses ConfigMap through environment variables

Example:
Create a ConfigMap first

# Create a ConfigMap
 [root@master01 ~]# echo 'apiVersion: v1
 kind: ConfigMap
 metadata:
   name: special-config
 data:
   USER_NAME: huangsir
   APP: haha
   COLOR: red
 ---
 apiVersion: v1
 kind: ConfigMap
 metadata:
   name: env-config
   namespace: default
 data:
   USER_AGE: "18"
   USER_NAME: zhangsan
   USER_ADDR: beijing' | kubectl apply -f -

Use the contents of ConfigMap as the environment variable for the Pod:

# Create a Pod
 [root@master01 ~/configmap]# echo 'apiVersion: v1
 kind: Pod
 metadata:
   name: env-configmap-pod
 spec:
   containers:
     - name: app
       # Print environment variables
       command: ["/bin/sh", "-c", "printenv"]
       image: busybox:latest
       # Specify where the env comes from
       envFrom:
         # ConfigMap reference
         - configMapRef:
             # Specify the name of the ConfigMap to be referenced
             name: env-config' | kubectl apply -f -

 # Check whether the Pod's log prints the configured environment variables
 [root@master01 ~/configmap]# kubectl logs env-configmap-pod | grep USER
 USER_ADDR=beijing
 USER_AGE=18
 USER_NAME=zhangsan

Specify the environment variable of the Pod to be the Key in ConfigMap

Example:

# Create a Pod
 echo 'apiVersion: v1
 kind: Pod
 metadata:
   name: env-configmap-pod-1
 spec:
   containers:
     - name: app
       # Print environment variables
       command: ["/bin/sh", "-c", "printenv"]
       image: busybox:latest
       env:
       # Specify the key of the environment variable in the Pod
       - name: POD-NAME
         # Specify where to get the value of the environment variable
         valueFrom:
           # Specify to get from ConfigMap
           configMapKeyRef:
             # Specify the name of the ConfigMap
             name: special-config
             # Specify that the key exists in ConfigMap
             key: USER_NAME
       # Multiple values ​​can be defined
       - name: POD-ADDR
         valueFrom:
           configMapKeyRef:
             name: env-config
             key: USER_ADDR' | kubectl apply -f -

 # View environment variables printed in the log
 [root@master01 ~/configmap]# kubectl logs env-configmap-pod-1 | grep POD
 POD-ADDR=beijing
 POD-NAME=huangsir

Pod uses ConfigMap through storage volume mount

Create a ConfigMap

[root@master01 ~/configmap]# echo 'apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  : |
    =jdbc:mysql://localhost:3306/mydb
    =root
    =password
  : |
    =INFO
    =/var/log/' | kubectl apply -f -

Create a Pod Mount ConfigMap

Method 1: Mount all Keys in ConfigMap to the path specified by the Pod. There are several things to note in this method:

  • If there are other files or directories in the directory where the Pod is mounted, it will be deleted
  • If the directory where the specified Pod is mounted does not exist, it will be automatically created
  • The corresponding file in the ConfigMap will be automatically created when mounted.

Example:

# Create a Pod
 echo 'apiVersion: v1
 kind: Pod
 metadata:
   name: volume-pod-1
 spec:
   containers:
     - name: app
       image: nginx:latest
       # Storage volume mount locally
       volumeMounts:
       # Name of the Pod storage volume mount
       - name: config-volume
         mountPath: /etc/config
   Volumes:
   - name: config-volume
     # Type of storage volume mount
     configMap:
       name: app-config' | kubectl apply -f -
	  
 # Verify the mount path
 [root@master01 ~/configmap]# kubectl exec -it volume-pod-1 -- ls -l /etc/config
 total 0
 lrwxrwxrwx 1 root root 24 May 2 07:50 -> ..data/
 lrwxrwxrwx 1 root root 21 May 2 07:50 -> ..data/

If you want to mount only part of the keys in ConfigMap and specify the file name to mount into the Pod, you can useitemsandsubPathFields to implement

Example:

# Create a Pod
 [root@master01 ~/configmap]# echo 'apiVersion: v1
 kind: Pod
 metadata:
   name: volume-pod-2
 spec:
   containers:
     - name: app
       image: nginx:latest
       # Storage volume mount locally
       volumeMounts:
       # Name of the Pod storage volume mount
       - name: config-volume
         mountPath: /etc/config/
         # When using the subPath attribute, mountPath does not execute a directory, but a file
         # Required conditions: Make sure the value of subPath is the same as the path value in the items list
         subPath:
   Volumes:
   - name: config-volume
     # Type of storage volume mount
     configMap:
       name: app-config
       Items:
       - key:
         path: ' | kubectl apply -f -

 # verify
 [root@master01 ~/configmap]# kubectl exec -it volume-pod-2 -- cat /etc/config/
 =INFO
 =/var/log/

ConfigMap with unchangeable configuration

A version of Kubernetes v1.21 provides an option to set individual Secrets and ConfigMaps to be unchangeable.

For clusters that use ConfigMap heavily (at least tens of thousands of different ConfigMaps are mounted to Pods), the following benefits are prohibited from changing the data of ConfigMap:

  • Protect the application from negative effects of unexpected (unwanted) updates.
  • Improve cluster performance by significantly reducing the pressure on kube-apiserver because the system shuts down monitoring operations for ConfigMaps marked as immutable.

Implementation method:

# Create an immutable ConfigMap by setting the immutable field to true
 apiVersion: v1
 kind: ConfigMap
 metadata:
   ...
 data:
   ...
 immutable: true

Once a ConfigMap is marked as immutable, the change cannot be reversed, nor can it be changed in the contents of the data or binaryData field. You can only delete and rebuild the ConfigMap. Because existing pods maintain a mount point for a deleted ConfigMap, it is recommended to recreate these pods.

The mounted ConfigMap content will be automatically updated

When the ConfigMap used in the Pod is updated, the corresponding key in the corresponding Pod will also be updated.
The kubelet component checks whether the mounted ConfigMap is up to date every time it is periodic. However, the kubelet uses its local cache to get the current value of the ConfigMap. The cache type can be passedfields to configure.

Note that the following two methods will not be updated and the pod needs to be restarted:

  • ConfigMap data used as environment variables will not be automatically updated.
  • Containers mounted with ConfigMap as subPath volume will not receive updates from ConfigMap.

Example: As abovePod uses ConfigMap through storage volume mountCome to verify

# Modify the mount content before ConfigMap
 # Pod1 content, mounted in the normal data volume
 [root@master01 ~]# kubectl exec -it volume-pod-1 -- cat /etc/config/
 =INFO
 =/var/log/
 # pod2 content, mount the subPath
 [root@master01 ~]# kubectl exec -it volume-pod-2 -- cat /etc/config/
 =INFO
 =/var/log/

 # Modify ConfigMap
 [root@master01 ~]# echo 'apiVersion: v1
 kind: ConfigMap
 metadata:
   name: app-config
 data:
   : |
     =jdbc:mysql://localhost:3306/mydb
     =root
     =password
   : |
     =error
     =/var/log/' | kubectl apply -f -

 # Verify that the modification is successful
 [root@master01 ~]# kubectl describe cm app-config
 Name: app-config
 Namespace: default
 Labels: <none>
 Annotations: <none>

 Data
 ====
 :
 ----
 =jdbc:mysql://localhost:3306/mydb
 =root
 =password

 :
 ----
 =error
 =/var/log/


 BinaryData
 ====

 Events: <none>

 # Verify that the internal pod is updated automatically
 # pod1 update successfully
 [root@master01 ~]# kubectl exec -it volume-pod-1 -- cat /etc/config/
 =error
 =/var/log/
 # pod2 not updated
 [root@master01 ~]# kubectl exec -it volume-pod-2 -- cat /etc/config/
 =INFO
 =/var/log/