0
0
KubernetesHow-ToBeginner · 3 min read

How to Mount Secret as Volume in Kubernetes

To mount a secret as a volume in Kubernetes, define a secret volume in your pod spec and then mount it inside a container using volumeMounts. This makes the secret data available as files inside the container at the specified path.
📐

Syntax

The pod specification requires two main parts to mount a secret as a volume:

  • volumes: Defines the secret volume by referencing the secret name.
  • volumeMounts: Mounts the secret volume inside the container at a chosen path.

This setup makes secret keys appear as files inside the container.

yaml
volumes:
  - name: secret-volume
    secret:
      secretName: my-secret

containers:
  - name: my-container
    image: nginx
    volumeMounts:
      - name: secret-volume
        mountPath: "/etc/secret-data"
        readOnly: true
💻

Example

This example shows a pod that mounts a secret named my-secret as a volume inside the container at /etc/secret-data. The secret keys become files inside that directory.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: secret-volume-pod
spec:
  containers:
    - name: secret-container
      image: busybox
      command: ["sleep", "3600"]
      volumeMounts:
        - name: secret-volume
          mountPath: "/etc/secret-data"
          readOnly: true
  volumes:
    - name: secret-volume
      secret:
        secretName: my-secret
Output
kubectl get pod secret-volume-pod NAME READY STATUS RESTARTS AGE secret-volume-pod 1/1 Running 0 10s kubectl exec secret-volume-pod -- ls /etc/secret-data password username
⚠️

Common Pitfalls

Common mistakes when mounting secrets as volumes include:

  • Using a secretName that does not exist, causing pod creation to fail.
  • Not setting readOnly: true which is recommended for security.
  • Mounting the secret volume at a path that conflicts with existing files.
  • Expecting the secret data as environment variables instead of files when mounted as volume.
yaml
volumes:
  - name: secret-volume
    secret:
      secretName: wrong-secret-name  # This secret does not exist

# Correct way:
volumes:
  - name: secret-volume
    secret:
      secretName: my-secret
📊

Quick Reference

FieldDescription
volumes[].nameName of the volume to reference in containers
volumes[].secret.secretNameName of the Kubernetes secret to mount
containers[].volumeMounts[].nameVolume name to mount inside container
containers[].volumeMounts[].mountPathPath inside container where secret files appear
containers[].volumeMounts[].readOnlySet to true to prevent writes to secret files

Key Takeaways

Mount secrets as volumes by defining a secret volume and mounting it inside the container.
Secret keys appear as files inside the container at the mount path.
Always verify the secret exists before referencing it in the pod spec.
Set volume mounts to readOnly for better security.
Avoid path conflicts by choosing a unique mount path inside the container.