Mounting Secrets as Volumes
What you'll learn: How to expose Kubernetes Secrets as files in a Pod's filesystem for applications that read credentials from disk rather than environment variables.
Why Mount Secrets as Files?
Some applications expect to read credentials from files on disk rather than environment variables. For example, database clients might look for a password in /etc/secrets/db-password, or TLS applications need certificate files at specific paths. Kubernetes lets you mount Secrets directly as volumes, making each key in the Secret appear as a separate file in the container's filesystem.
How It Works
Instead of injecting Secret values into environment variables (as in the previous lesson), you define a volume that references the Secret, then mount that volume into a specific directory in your container. Each key from the Secret becomes a file, and the file's content is the key's value.
YAML structure:
apiVersion: v1
kind: Pod
metadata:
name: secret-volume-pod
spec:
containers:
- name: app
image: nginx
volumeMounts:
- name: secret-vol
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secret-vol
secret:
secretName: my-secret
If my-secret contains keys username and password, the container will see two files: /etc/secrets/username and /etc/secrets/password, each containing the respective Secret value.
When to Use Volume Mounts vs Environment Variables
Use volume mounts when applications read config files, certificates, or keys from disk. Use environment variables for simple key-value settings.
Key Takeaway:
Mounting Secrets as volumes transforms each Secret key into a file in your Pod's filesystem, perfect for applications that read credentials from disk rather than environment variables.