Kubernetes Configmap: The Basics and a Quick Tutorial

What Is a Kubernetes ConfigMap? 

Kubernetes ConfigMap is a key-value store for configuration data inside Kubernetes clusters. It allows you to decouple configuration artifacts from image content to keep containerized applications portable. ConfigMaps can store configuration settings, command-line arguments, environment variables, and more, enabling dynamic updates to application settings without rebuilding containers.

ConfigMaps support various data formats like plain text, key-value pairs, or entire configuration files. They facilitate managing external configurations of your applications, aiding microservices architectures where different services might require varying configurations. Using ConfigMap ensures your application’s code and configuration are decoupled.
This is part of a series of articles about Kubernetes management

What Is a Kubernetes ConfigMap Used For? 

Kubernetes ConfigMaps are used for various purposes within a kubernetes cluster to manage configuration data for containerized applications. Here are the primary uses:

  • Decoupling configuration from application code: ConfigMaps allow you to separate configuration settings from the application code. This separation ensures that you can modify configuration data without rebuilding the application image, facilitating continuous deployment and environment-specific configurations.
  • Storing configuration data: ConfigMaps can store various types of configuration data, such as plain text, key-value pairs, and configuration files.
  • Dynamic configuration updates: By using ConfigMaps, you can dynamically update the configuration of running applications without restarting the containers.
  • Sharing configuration across multiple pods: ConfigMaps can be shared across multiple pods within the same namespace. This sharing capability is especially beneficial for microservices architectures, where multiple services might rely on common configuration settings.
  • Environment variable management: ConfigMaps are often used to define environment variables for containers. This approach simplifies the management of environment-specific settings.

How Often Is ConfigMap Data Updated?

When a ConfigMap is mounted as a volume in a pod, any updates to the ConfigMap are eventually reflected in the pod’s file system. 

The kubelet, which is the primary node agent that runs on each node, periodically checks the mounted ConfigMap for updates. By default, the kubelet uses a watch mechanism to monitor changes. This watch mechanism allows the kubelet to detect updates and apply them to the pod’s file system. However, the exact timing of these updates depends on the kubelet’s sync period and the cache propagation delay.

The kubelet employs a local cache to manage the ConfigMap data. This cache can be configured to use different strategies for detecting changes:

  • Watch-based: This is the default method, where the kubelet watches for changes to the ConfigMap and updates the volume accordingly.
  • TTL-based (time-to-live): This method uses a time-to-live setting to periodically refresh the cache.
  • API server redirect: This method bypasses the cache and directly queries the API server for the latest ConfigMap data.

Depending on the chosen strategy, the delay from the ConfigMap update to the projection of new keys in the pod can vary. It can be as short as the watch propagation delay, the TTL of the cache, or zero in the case of direct API server queries.

expert-icon-header

Tips from the expert

Itiel Shwartz

Co-Founder & CTO

Itiel is the CTO and co-founder of Komodor. He’s a big believer in dev empowerment and moving fast, has worked at eBay, Forter and Rookout (as the founding engineer). Itiel is a backend and infra developer turned “DevOps”, an avid public speaker that loves talking about things such as cloud infrastructure, Kubernetes, Python, observability, and R&D culture.

In my experience, here are tips that can help you better leverage Kubernetes ConfigMaps:

Implement default fallbacks in your application:

When using ConfigMaps, ensure your application has sensible default values if certain keys are missing. This prevents failures due to misconfigurations or missing ConfigMap entries.

Namespace-specific naming conventions:

Adopt a naming convention for ConfigMaps that includes the namespace or application name as a prefix. This practice avoids conflicts and makes it easier to manage ConfigMaps across different environments or teams.

Limit the size of ConfigMaps:

Kubernetes imposes a limit of 1MB per ConfigMap. Plan your ConfigMaps to avoid hitting this limit by breaking large configurations into multiple smaller ConfigMaps, where applicable.

Monitor ConfigMap usage and performance impacts:

Excessive or overly frequent updates to ConfigMaps can strain the API server and kubelet. Monitor the performance impact of ConfigMap usage, especially in high-churn environments.

Test ConfigMap updates in non-production environments:

Before applying ConfigMap updates to production, test them in a staging or development environment. This reduces the risk of introducing errors that could impact production workloads.

Quick Tutorial: Configure a Pod to Use a ConfigMap

Example of a ConfigMaps Used by a Pod 

A ConfigMap can be referenced in a pod specification to configure the container(s) within that pod using data from the ConfigMap. It’s important to note that the pod and the ConfigMap must exist within the same namespace.

Here’s an example of a ConfigMap that includes both single-value keys and file-like keys:

apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database_url: "jdbc:mysql://localhost:3306/mydb"
log_level: "debug"
app.properties: |
feature.x.enabled=true
max.connections=10
database-config.properties: |
db.username=admin
db.password=secret

Let’s store above code in app-config.yaml and apply it using the following command:

kubectl apply -f app-config.yaml

Here’s an example of a pod that uses the app-config ConfigMap:

apiVersion: v1
kind: Pod
metadata:
name: configmap-example-pod
spec:
containers:
- name: myapp-container
image: busybox
command: ["sleep", "3600"]
env:
- name: DATABASE_URL
valueFrom:
configMapKeyRef:
name: app-config
key: database_url
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: log_level
volumeMounts:
- name: config-volume
mountPath: "/etc/config"
readOnly: true
volumes:
- name: config-volume
configMap:
name: app-config
items:
- key: "app.properties"
path: "app.properties"
- key: "database-config.properties"
path: "database-config.properties"

Let’s store the above code in a file called pod.yaml. We can apply it using the following command:

kubectl apply -f pod.yaml

Using ConfigMaps as Files from a Pod

To consume a ConfigMap as a volume in a pod, follow these steps:

  1. Create or use an existing ConfigMap.
  2. Modify your pod definition to add a volume under .spec.volumes[] and reference the ConfigMap.
  3. Add a .spec.containers[].volumeMounts[] entry for each container that needs the ConfigMap.

Here’s an example:

apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mypod
image: redis
volumeMounts:
- name: foo
mountPath: "/etc/configmount"
readOnly: true
volumes:
- name: foo
configMap:
name: app-config

Let’s store this file as configmap-frompod.yaml, we can apply it using the following command:

kubectl apply -f configmap-frompod.yaml

Using ConfigMaps as Environment Variables

To use a ConfigMap as an environment variable, add an environment variable entry in the pod specification for each key from the ConfigMap:

apiVersion: v1
kind: Pod
metadata:
name: env-configmap
spec:
containers:
- name: my-test-container
image: busybox
env:
- name: CONFIGMAP_PASSWORD
valueFrom:
configMapKeyRef:
name: app-config
key: password

The output of the command ConfigMap app-config should look like the following:

Immutable ConfigMaps

Starting from kubernetes v1.21, ConfigMaps can be set as immutable. This prevents accidental updates that could cause outages and reduces the load on the API server. To create an immutable ConfigMap, set the immutable field to true:

apiVersion: v1
kind: ConfigMap
metadata:
...
data:
...
immutable: true

Once marked as immutable, you cannot modify the ConfigMap. The only way to change it is to delete and recreate it, which requires recreating any pods that reference it.

Best Practices for ConfigMaps 

Keeping Configuration Separate from Application Code

Separating configuration from application code is crucial for maintainability and portability. ConfigMaps provide a way to externalize the configuration, ensuring that application binaries remain unchanged across different environments. This practice enhances reusability and simplifies configuration management.

By keeping configuration data in ConfigMaps, any configuration changes can be applied without modifying the application image. This is especially beneficial for continuous deployment pipelines, where different stages require different settings without impacting the application codebase.

Managing Different Configurations for Different Environments

Managing configurations across multiple environments is simplified using ConfigMaps. Each environment, such as development, testing, and production, can have its own ConfigMap tailored to the specific configurations required. This allows a single application container to adapt to different environments by referencing the corresponding ConfigMap.

This method ensures that the configurations are consistent and appropriate for each environment. By isolating environment-specific settings within ConfigMaps, developers can easily manage and update configurations without affecting other environments, enhancing deployment flexibility and stability.

Using ConfigMaps in Conjunction with Secrets for Sensitive Data

While ConfigMaps are ideal for managing non-sensitive configuration data, kubernetes Secrets should be used for sensitive information like passwords, tokens, and keys. Combining ConfigMaps with Secrets ensures that configuration data and sensitive information are managed securely and efficiently.

In scenarios where both types of data need to coexist, use ConfigMaps for general configuration and Secrets for sensitive data. This segregation ensures a higher security level and aligns with best practices for handling sensitive information in kubernetes environments, helping to mitigate risk and improve security posture.

Storing ConfigMap Data in Version Control Systems

Storing ConfigMap data in version control systems (VCS) is a best practice that enhances traceability and collaboration. By committing ConfigMap definitions to a VCS, teams can track changes, review history, and collaborate more effectively. This approach ensures that configuration changes are documented and can be easily rolled back if necessary.

Version-controlling ConfigMaps alongside application code aligns the configuration lifecycle with the development process. This practice improves transparency and aids in the deployment of applications across diverse environments.

Simplifying Kubernetes Management with Komodor

Komodor is the Continuous Kubernetes Reliability Platform, designed to democratize K8s expertise across the organization and enable engineering teams to leverage its full value.

Komodor’s platform empowers developers to confidently monitor and troubleshoot their workloads while allowing cluster operators to enforce standardization and optimize performance. Specifically when working in a hybrid environment, Komodor reduces the complexity by providing a unified view of all your services and clusters.

By leveraging Komodor, companies of all sizes significantly improve reliability, productivity, and velocity. Or, to put it simply – Komodor helps you spend less time and resources on managing Kubernetes, and more time on innovating at scale.

If you are interested in checking out Komodor, use this link to sign up for a Free Trial.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 5

No votes so far! Be the first to rate this post.