Distribute credentials with Secrets

Updated at:

When deploying applications, manage database passwords, API keys, and other sensitive data with Secrets instead of hard-coding credentials in application code. Store credentials in Secrets and distribute them to pods as volumes or environment variables.

Prerequisites

Before you begin, make sure you have:

Background

Pods can consume a Secret in two ways:

  • Mount the Secret as a volume to the pod.

  • Expose the Secret as environment variables for the pod.

See Kubernetes Secrets.

Which method to use

Method Features Scenarios
Volume mount (recommended) File permissions isolate the credentials from other processes. File content is automatically synchronized. Recommended for production environments, especially for highly sensitive data such as database passwords and API keys, and for scenarios that require fine-grained file permission control.
Environment variable injection Environment variables can be accessed by all processes and may be exposed in logs. Configuration updates take effect only after the pod is restarted. Simple and fast configuration injection. Suitable for values such as log levels and service addresses, or for legacy applications that already read data from environment variables.

Create a Secret

These steps create a Secret named nginx-secret that stores a username, a password, and an API key.

Secret values must be Base64-encoded. To encode a value, run echo -n 'your-value' | base64.

Use the console

  1. Log on to the ACK console and click Clusters in the left navigation pane.

  2. On the Clusters page, find the target cluster and click its name. In the left pane, choose Configurations > Secrets.

  3. On the Secrets page, select a namespace (default), and then click Create in the upper-right corner. In the panel that appears, configure the Secret.

    • Name: nginx-secret

    • Select a Type for the Secret. The following types are supported:

      • Opaque: a Base64-encoded Secret that stores sensitive data such as passwords and certificates. This example uses Opaque.

      • Image pull credential: stores the credential used to access a private image registry.

      • TLS certificate: stores a TLS/SSL certificate and its private key.

    • Add or remove key data:

      • username: admin

      • password: 'MySecurePassword!'

      • api-key: 'ak-1234567890abcdef'

      If you enter the data in plaintext, select Encode Data Values Using Base64.

Use the CLI

  1. Connect to the cluster with kubectl.

  2. Create the Secret.

    kubectl create secret generic nginx-secret \
      --from-literal=username=admin \
      --from-literal=password='MySecurePassword!' \
      --from-literal=api-key='ak-1234567890abcdef' \
      -n default
  3. View the Secret.

    kubectl get secret nginx-secret

    Expected output:

    NAME           TYPE     DATA   AGE
    nginx-secret   Opaque   3      23h

Alternatively, manage Secrets on the Secrets page after the Secret is created.

Mount a Secret as a volume

A Deployment and its Secret must be in the same namespace.

This method mounts the Secret as files so that the application reads sensitive data, such as certificates, private keys, and configuration files, as local files. Each key in the Secret becomes a file in the mount directory, with the value as file content.

Use the CLI

This example mounts nginx-secret into pods at /etc/nginx/secrets, making the username, password, and api-key keys available as files.

Create a file named nginx-volume-demo.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-volume-demo
  namespace: default
  labels:
    app: nginx-volume
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-volume
  template:
    metadata:
      labels:
        app: nginx-volume
    spec:
      containers:
      - name: nginx
        image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
        ports:
        - containerPort: 80
          protocol: TCP
        # Mount the Secret as a volume
        volumeMounts:
        - name: secret-volume
          mountPath: /etc/nginx/secrets
          readOnly: true
      volumes:
      - name: secret-volume
        secret:
          secretName: nginx-secret
          # Set the file permissions of the mounted keys
          defaultMode: 0644
          # Optional: map keys to custom file names
          items:
          - key: username
            path: db-username.txt
          - key: password
            path: db-password.txt
          - key: api-key
            path: api-key.txt

Apply the manifest:

kubectl apply -f nginx-volume-demo.yaml

Check the pod status:

kubectl get pods -l app=nginx-volume -n default

Expected output:

NAME                                  READY   STATUS    RESTARTS   AGE
nginx-volume-demo-7db46895bc-c98b5   1/1     Running   0          4h20m
nginx-volume-demo-7db46895bc-pc6qg   1/1     Running   0          4h20m

Verify that the Secret files are mounted:

kubectl exec deployment/nginx-volume-demo -n default -- ls -la /etc/nginx/secrets

Expected output:

total 4
drwxrwxrwt 3 root root  140 Sep 15 02:31 .
drwxr-xr-x 1 root root 4096 Sep 15 02:31 ..
drwxr-xr-x 2 root root  100 Sep 15 02:31 ..2025_09_15_02_31_13.2599431463
lrwxrwxrwx 1 root root   32 Sep 15 02:31 ..data -> ..2025_09_15_02_31_13.2599431463
lrwxrwxrwx 1 root root   18 Sep 15 02:31 api-key.txt -> ..data/api-key.txt
lrwxrwxrwx 1 root root   22 Sep 15 02:31 db-password.txt -> ..data/db-password.txt
lrwxrwxrwx 1 root root   22 Sep 15 02:31 db-username.txt -> ..data/db-username.txt

Verify that the file content is correct:

kubectl exec deployment/nginx-volume-demo -n default -- cat /etc/nginx/secrets/db-username.txt
kubectl exec deployment/nginx-volume-demo -n default -- cat /etc/nginx/secrets/api-key.txt

Expected output:

admin
ak-1234567890abcdef

If the output matches the data configured in the Secret, the application can read the Secret data from the mounted volume.

Use the console

  1. Log on to the ACK console and click Clusters in the left navigation pane.

  2. On the Clusters page, find the target cluster and click its name. In the left pane, choose Workloads > Deployments.

  3. On the Deployments page, click Create from Image to create a Deployment. See Create a stateless application by using a Deployment.

    If you already have a Deployment, choose Workloads > Deployments, and edit the volume settings of the container as described in the following example.
  4. On the Basic Information wizard page, configure the parameters and click Next.

    • Application name: nginx-volume-demo

    • Namespace: default

    • Replicas: 2

    • Type: Stateless (Deployment)

  5. On the Container wizard page, configure Image Name and Port.

    • Image Name: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6

    • Container Port: 80, protocol TCP

    Important

    The cluster must be able to access the Internet before it pulls this image. If you selected Configure SNAT for VPC when you created the cluster, which is enabled by default, no additional configuration is required. Otherwise, see Enable Internet access for an existing ACK cluster.

  6. On the Container wizard page, go to the Volume section and click Add Local Storage. Set these fields, then click Next:

    Field Value
    PV Type Secret
    Name secret-volume
    Mount Source The Secret created in Create a Secret, for example nginx-secret
    Container Path The path to which the Secret is mounted in the container, for example /etc/nginx/secrets

    Configure volume

  7. On the Advanced Settings wizard page, configure scaling, scheduling, and annotations as needed, and then click Create at the bottom of the page.

  8. On the Complete page, view the application task and check whether the pods are in the Running state.

  9. Verify that the Secret files are mounted.

    Select the container that you want to log on to, for example nginx-volume-demo-7xxxxxx****, click Terminal in the Actions column, and then select nginx to log on to the container.

    List the files in the mount directory:

    ls -la /etc/nginx/secrets

    Expected output:

    total 4
    drwxrwxrwt 3 root root  140 Sep 15 02:31 .
    drwxr-xr-x 1 root root 4096 Sep 15 02:31 ..
    drwxr-xr-x 2 root root  100 Sep 15 02:31 ..2025_09_15_02_31_13.2599431463
    lrwxrwxrwx 1 root root   32 Sep 15 02:31 ..data -> ..2025_09_15_02_31_13.2599431463
    lrwxrwxrwx 1 root root   18 Sep 15 02:31 api-key.txt -> ..data/api-key.txt
    lrwxrwxrwx 1 root root   22 Sep 15 02:31 db-password.txt -> ..data/db-password.txt
    lrwxrwxrwx 1 root root   22 Sep 15 02:31 db-username.txt -> ..data/db-username.txt

    Verify that the file content is correct:

    cat /etc/nginx/secrets/db-username.txt
    cat /etc/nginx/secrets/api-key.txt

    Expected output:

    admin
    ak-1234567890abcdef

    If the output matches the data configured in the Secret, the application can read the Secret data from the mounted volume.

Expose a Secret as environment variables

A Deployment and its Secret must be in the same namespace.

This method injects sensitive data, such as passwords, API keys, and tokens, into containers as environment variables, which separates configuration from code. Each key-value pair in the Secret maps to an environment variable in the container.

Use the CLI

This example references the username, password, and api-key keys of nginx-secret as the environment variables DB_USERNAME, DB_PASSWORD, and API_KEY, and injects all keys at once with envFrom.

Create a file named nginx-env-demo.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-env-demo
  namespace: default
  labels:
    app: nginx-env
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-env
  template:
    metadata:
      labels:
        app: nginx-env
    spec:
      containers:
      - name: nginx
        image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
        ports:
        - containerPort: 80
          protocol: TCP
        # Inject individual Secret key-value pairs
        env:
        - name: DB_USERNAME
          valueFrom:
            secretKeyRef:
              name: nginx-secret
              key: username
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: nginx-secret
              key: password
        - name: API_KEY
          valueFrom:
            secretKeyRef:
              name: nginx-secret
              key: api-key
        # Optional: inject all Secret key-value pairs at once
        envFrom:
        - prefix: NGINX_
          secretRef:
            name: nginx-secret

Apply the manifest:

kubectl apply -f nginx-env-demo.yaml

Check the pod status:

kubectl get pods -l app=nginx-env -n default

Expected output:

NAME                             READY   STATUS    RESTARTS   AGE
nginx-env-demo-6dc7556d9-6pjhj   1/1     Running   0          3h33m
nginx-env-demo-6dc7556d9-rcqsh   1/1     Running   0          3h33m

Verify that the environment variables are injected:

kubectl exec deployment/nginx-env-demo -n default -- env | grep -E 'DB_|API_|NGINX_'

Expected output:

API_KEY=ak-1234567890abcdef
NGINX_api-key=ak-1234567890abcdef
NGINX_password=MySecurePassword!
NGINX_username=admin
DB_USERNAME=admin
DB_PASSWORD=MySecurePassword!

If the output matches the data configured in the Secret, the application can read the Secret data from environment variables.

Use the console

  1. Log on to the ACK console and click Clusters in the left navigation pane.

  2. On the Clusters page, find the target cluster and click its name. In the left pane, choose Workloads > Deployments.

  3. On the Deployments page, click Create from Image to create a Deployment. See Create a stateless application by using a Deployment.

    If you already have a Deployment, choose Workloads > Deployments, and edit the environment variables of the container as described in the following example.
  4. On the Basic Information wizard page, configure the parameters and click Next.

    • Application name: nginx-env-demo

    • Namespace: default

    • Replicas: 2

    • Type: Stateless (Deployment)

  5. On the Container wizard page, configure Image Name and Port.

    • Image Name: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6

    • Container Port: 80, protocol TCP

    Important

    The cluster must be able to access the Internet before it pulls this image. If you selected Configure SNAT for VPC when you created the cluster, which is enabled by default, no additional configuration is required. Otherwise, see Enable Internet access for an existing ACK cluster.

  6. On the Container wizard page, go to the Environment Variable section and click Add. Set these fields for each environment variable:

    Field Value
    Type Secrets
    Variable name The name of the environment variable (such as USERNAME)
    Value/ValueFrom Select the Secret created in Create a Secret, for example nginx-secret, and then map each key of the Secret (username, password, or api-key) to an environment variable name

    Configure environment variables

  7. On the Advanced Settings wizard page, configure scaling, scheduling, and annotations as needed, and then click Create at the bottom of the page.

  8. On the Complete page, view the application task and check whether the pods are in the Running state.

  9. Verify that the environment variables are injected.

    Select the container that you want to log on to, for example nginx-env-demo-7xxxxxx****, click Terminal in the Actions column, and then select nginx to log on to the container.

    env | grep -E 'DB_|API_|NGINX_'

    Expected output:

    API_KEY=ak-1234567890abcdef
    NGINX_api-key=ak-1234567890abcdef
    NGINX_password=MySecurePassword!
    NGINX_username=admin
    DB_USERNAME=admin
    DB_PASSWORD=MySecurePassword!

    If the output matches the data configured in the Secret, the application can read the Secret data from environment variables.

Manage Secrets

After a Secret is created, you can perform the following operations on the Secrets page:

Operation Description
View a Secret Click the name of the target Secret to view its basic information and detailed information.
Edit a Secret

Click Edit in the Actions column to modify the Secret.

Important

Modifying a Secret that is in use may interrupt your workloads. Proceed with caution.

Delete a Secret

Click Delete in the Actions column to delete a Secret that you no longer need.

Important

Do not delete the Secrets that are automatically created in the kube-system and kube-public namespaces when the cluster is created, such as the Secrets of service accounts.

Related documents