Updated on 2026-07-07 GMT+08:00

Secrets

Secrets let you store and manage confidential information, such as authentication details, certificates, and private keys. Storing confidential information in a secret is safer and more flexible than putting it in a pod specification or a container image.

Similar to ConfigMaps, secrets store data in key-value pairs. The difference is that secrets are encrypted, so they are suitable for storing confidential information.

Base64 Encoding

A secret stores data in key-value pairs, the same form as that of a ConfigMap. The difference is that values of a secret must be encoded using Base64 when the secret is created.

To encode a character string using Base64, run the echo -n <content-to-be-encoded> | base64 command. Here is an example:

root@ubuntu:~# echo -n "3306" | base64
MzMwNg==

Creating a Secret

The secret defined in the following example contains two key-value pairs.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
data:
  key1: aGVsbG8gd29ybGQ=   # The Base64-encoded value of hello world
  key2: MzMwNg==           # The Base64-encoded value of 3306

Referencing a Secret as an Environment Variable

Secrets are usually injected into containers as environment variables. The following shows an example.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    env:
    - name: key
      valueFrom:
        secretKeyRef:
          name: mysecret
          key: key1
  imagePullSecrets:
  - name: default-secret

Referencing a Secret in a Volume

Referencing a secret in a volume is when you save the data as configuration files in the volume. Each piece of data is saved as an individual file. The key is the file name, and the key value is the file content.

In the following example, a volume named vol-secret is created, a secret named mysecret is referenced in the volume, and the volume is mounted to the /tmp directory of the container. After the pod is created, two files key1 and key2 are generated in the /tmp directory of the container.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    volumeMounts:
    - name: vol-secret              # Mount the volume named vol-secret.
      mountPath: "/tmp"
  imagePullSecrets:
  - name: default-secret
  volumes:
  - name: vol-secret
    secret:                         # Reference a secret.
      secretName: mysecret

In the container, you can find the two files key1 and key2 in the /tmp directory and see the Base64-decoded key values, hello world and 3306.