Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 311 of 8025. Advanced Kubernetes ConfigurationFree lesson

Mounting Secrets as Files in Container Volumes

Implement volume mounts to expose sensitive configuration files directly into the container filesystem for applications requiring file-based secrets.

In this lesson, you will learn how to expose sensitive data, such as private keys or database credentials, as actual files inside your container’s filesystem using Kubernetes volumes.

Why use files instead of environment variables?

While injecting Secrets as environment variables is convenient, it has drawbacks. Environment variables are often logged by system processes, visible in crash reports, and cannot be updated without restarting the Pod. By mounting a Secret as a volume, Kubernetes creates a directory inside your container where each key in the Secret becomes an individual file, and the value becomes the file's content. This is the preferred method for applications (like NGINX or Postgres) that expect to read configuration from specific file paths.

Implementing a Secret Volume Mount

To mount a Secret, you first reference it in the volumes section of your Pod specification, then mount that volume into the container section.

apiVersion: v1
kind: Pod
metadata:
  name: secure-app
spec:
  containers:
  - name: my-app
    image: nginx
    volumeMounts:
    - name: secret-volume
      mountPath: /etc/app/secrets
      readOnly: true
  volumes:
  - name: secret-volume
    secret:
      secretName: my-db-credentials

When this Pod starts, Kubernetes creates a folder at /etc/app/secrets. If your my-db-credentials Secret contains a key named password, the container will see a file located at /etc/app/secrets/password. Your application can simply read this file to obtain the secret value.

Key Benefits

  • Security: Sensitive data is kept out of process environment dumps.
  • Compatibility: It supports applications that require file-based configuration (e.g., TLS certificates or .key files).
  • Dynamic Updates: Unlike environment variables, when you update a Secret, Kubernetes automatically updates the mounted files inside the running container (though the application must be designed to re-read the files).

Key Takeaway: Mounting Secrets as volumes provides a secure, file-system-native way to provide sensitive configuration to applications, overcoming the limitations and risks associated with environment variables.