ConfigMaps and Secrets in Kubernetes: examples as environment variables and files
Why ConfigMaps and Secrets are essential
In Kubernetes, separating code and configuration is a best practice that enables repeatable, secure, and portable deployments. ConfigMap and Secret are the key resources for managing configurations and credentials declaratively. ConfigMaps contain non-sensitive configurations (e.g., flags, URLs, feature toggles), while Secrets manage sensitive data (e.g., passwords, tokens, certificates). Both can be exposed to Pods as environment variables or as mounted files, enabling flexible integration with applications.
ConfigMap vs Secret: differences at a glance
A ConfigMap is intended for non-confidential data and is stored in plaintext in the cluster. A Secret is designed to hold sensitive information: in manifests they may appear in base64 (or via stringData in plaintext, which the server converts), and in the cluster they can be protected with encryption at rest if enabled. Both have size limits (about 1 MiB per object) and are namespaced. By default, Secrets mounted as a volume are kept in memory by the kubelet. To increase security, enable encryption at rest, restrict access with RBAC, and avoid committing secrets to unsecured repositories.
Quick creation from the command line
Here’s how to create a ConfigMap and a Secret with kubectl using literal values and files.
# ConfigMap with key=value pairs kubectl create configmap app-config --from-literal=color=blue --from-literal=greeting="Hello world" # Secret with literal values and from file (api-key from apikey.txt) kubectl create secret generic app-secret --from-literal=db-password='S3cr3t!' --from-file=api-key=./apikey.txt
Alternatively, define them via YAML manifests (useful for GitOps). Note the use of stringData to simplify handling Secrets in plaintext on the client side, which the server will then transform into base64-encoded data.
apiVersion: v1 kind: ConfigMap metadata: name: app-config data: color: blue greeting: "Hello world" --- apiVersion: v1 kind: Secret metadata: name: app-secret type: Opaque stringData: db-password: "S3cr3t!" api-key: "abc123"
Using ConfigMap and Secret as environment variables
Mounting values as environment variables is straightforward and makes them immediately available to the application process. It’s ideal for small amounts of configuration. Remember: environment variables do not update automatically if ConfigMaps/Secrets change; you need to restart the Pod or roll out a new Deployment revision.
Selective with valueFrom (keyRef)
This approach is useful when you want to expose specific keys with explicit environment variable names.
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 1
selector:
matchLabels:
app: webapp
template:
metadata:
labels:
app: webapp
spec:
containers:
- name: app
image: nginx:1.25-alpine
env:
- name: APP_COLOR
valueFrom:
configMapKeyRef:
name: app-config
key: color
- name: APP_GREETING
valueFrom:
configMapKeyRef:
name: app-config
key: greeting
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: app-secret
key: db-password
Bulk import with envFrom
With envFrom you can bring all key=value pairs from a ConfigMap or a Secret directly into the container’s environment variables. Pay attention to names to avoid conflicts and consider whether it’s appropriate to expose all secrets as variables.
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp-envfrom
spec:
replicas: 1
selector:
matchLabels:
app: webapp-envfrom
template:
metadata:
labels:
app: webapp-envfrom
spec:
containers:
- name: app
image: nginx:1.25-alpine
envFrom:
- configMapRef:
name: app-config
- secretRef:
name: app-secret
Mounting ConfigMap and Secret as files
When your application reads configurations from files (e.g., YAML, JSON, certs, keys), mounting as a volume is the best choice. Unlike environment variables, volume mounts can reflect updates (without restarting Pods) within a short kubelet sync interval, as long as you don’t use subPath and the app rereads the files.
Example: mount a ConfigMap as files
In this example, we mount some keys as files in a dedicated directory and set read-only permissions.
apiVersion: v1
kind: Pod
metadata:
name: config-file-pod
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh","-c","ls -l /etc/myapp/config && cat /etc/myapp/config/greeting.txt && sleep 3600"]
volumeMounts:
- name: app-config-vol
mountPath: /etc/myapp/config
readOnly: true
volumes:
- name: app-config-vol
configMap:
name: app-config
items:
- key: greeting
path: greeting.txt
Example: mount a Secret as files
With Secrets, it’s common to mount certificates, keys, or passwords as separate files with more restrictive permissions.
apiVersion: v1
kind: Pod
metadata:
name: secret-file-pod
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh","-c","ls -l /etc/myapp/secret && sleep 3600"]
volumeMounts:
- name: app-secret-vol
mountPath: /etc/myapp/secret
readOnly: true
volumes:
- name: app-secret-vol
secret:
secretName: app-secret
defaultMode: 0400
The defaultMode field sets the Unix permissions of the generated files. You can also use items to map individual keys to specific paths or rename the files.
Updates, rotations, and reloads
If you mount as environment variables, Pods won’t see changes until they are restarted or redeployed. With ConfigMap/Secret-based volumes, changes are propagated to mounted files within a few seconds, but the app must reread them or support reload. Common strategies include sidecars that watch for file changes and send a reload signal (e.g., SIGUSR1 or SIGHUP) to the main process.
Security and management best practices
– Minimize the surface area: include only the necessary keys in each Pod, using items or targeted keyRefs.
– Apply restrictive RBAC: allow ServiceAccounts and users to read only the strictly necessary resources.
– Enable encryption at rest for Secrets in etcd and use encrypted channels (TLS) for all communications.
– Do not store Secrets in plaintext in public repositories. Consider solutions such as Sealed Secrets, External Secrets Operator, or integrations with external vaults (HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager).
– Avoid passing secrets as command-line arguments, because they may appear in logs or the process list.
– Name keys and files consistently to facilitate versioning and migration.
Debugging and troubleshooting
If the variables don’t appear, verify that the key exists and that the names match. Check events and resource details with the following commands.
# Inspect ConfigMap and Secret kubectl describe configmap app-config kubectl describe secret app-secret # Verify the files mounted in the Pod kubectl exec -it config-file-pod -- ls -l /etc/myapp/config kubectl exec -it secret-file-pod -- ls -l /etc/myapp/secret # Check env vars (for containers that expose a shell) kubectl exec -it webapp-xxxxxxxxx-xxxxx -- printenv | grep -E 'APP_|DB_'
If files don’t update, make sure you’re not using subPath in the volumeMount, verify that the app rereads the files, and that the kubelet is synchronizing correctly.
When to choose env vs files
– Environment variables: ideal for small sets of simple options, with a restart required to refresh values.
– Mounted files: perfect for structured configurations, certificates, and credentials. They support dynamic updates and granular permissions.
Conclusion
ConfigMaps and Secrets provide a powerful and flexible infrastructure for managing application configuration in Kubernetes. Knowing when to use them as environment variables and when to mount them as files, how to organize them, and how to protect them makes the difference between a fragile environment and a reliable, scalable, and secure system. Implement these patterns in your workflow today and optimize your applications’ lifecycle.
Ready to put these examples into practice?
If you want a review of your manifests or step-by-step guidance to migrate configurations to ConfigMaps and Secrets, contact us: we can help you design a solid, secure, and automatable strategy for your Kubernetes environments.

Comments