In this lesson, you will learn how to protect your application’s sensitive credentials, such as API keys and database passwords, by using Kubernetes Secrets instead of ConfigMaps.
Why Secrets instead of ConfigMaps?
In our previous lessons, we learned how to use ConfigMaps to store configuration data. While excellent for general settings, ConfigMaps store data in plain text, making them unsuitable for sensitive information like DB_PASSWORD or STRIPE_API_KEY. If someone gains access to your cluster configuration, they would instantly see those passwords. Kubernetes Secrets solve this by providing a dedicated object type designed to hold confidential data securely.
Creating a Secret
A Secret works similarly to a ConfigMap, but it expects your data to be base64 encoded. You can create one easily using the kubectl command:
kubectl create secret generic db-credentials \
--from-literal=username=admin \
--from-literal=password=super-secret-123
Behind the scenes, Kubernetes stores this object as a Secret resource. When you want to use this in a Pod, you reference it just like you would a ConfigMap, either as an environment variable or a mounted volume.
Here is how you inject it as an environment variable in a Pod definition:
spec:
containers:
- name: my-app
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
Key Security Considerations
By using a Secret, you ensure that sensitive data is not stored as plain text in your version control systems (like Git) or directly in your manifest files. Furthermore, Kubernetes Secrets are only sent to nodes that specifically require them, and they are kept in memory rather than being written to the disk of the node whenever possible. This layer of abstraction keeps your sensitive data isolated from your general application configuration, making your cluster significantly more resilient against configuration leaks.
Key Takeaway: Use Kubernetes Secrets for sensitive credentials to prevent plain-text exposure, keeping your application security decoupled from your general configuration.