Ctrl + K
Kubernetes12 min read

Kubernetes Secrets Explained

Understand how Kubernetes Secrets store sensitive configuration such as passwords, tokens and certificates, and learn how to use them securely with Pods and Deployments.

Published: 2026-09-02

Kubernetes Secrets are API objects designed to store sensitive information separately from application containers and ordinary configuration. They are commonly used for passwords, API tokens, authentication credentials, TLS certificates and other values that should not be placed directly inside application manifests or container images.

Secrets can be consumed by Pods as environment variables, mounted as files or referenced by other Kubernetes resources. Although Secrets provide useful mechanisms for handling sensitive configuration, they should not be treated as automatically secure storage without considering encryption, access control and cluster security.

What Is a Kubernetes Secret?

A Secret is a Kubernetes resource that stores a small amount of sensitive data. Instead of putting a database password directly into a Deployment manifest, for example, an administrator can store the value in a Secret and allow only the required workloads to access it.

Why Use Secrets?

  • Keep passwords outside application images.
  • Store API tokens and credentials separately from ordinary configuration.
  • Provide sensitive values to containers at runtime.
  • Mount certificates and keys as files.
  • Control access to sensitive configuration through Kubernetes permissions.
  • Separate application code from environment-specific credentials.

Basic Secret Example

A Secret manifest uses the Secret resource type. Values in the data field are represented using base64 encoding rather than ordinary plain text.

apiVersion: v1
kind: Secret
metadata:
  name: app-credentials
type: Opaque
data:
  username: YWRtaW4=
  password: c3VwZXJzZWNyZXQ=
⚠️ Base64 is encoding, not encryption. Anyone who can read the Secret data can decode base64 values. Protecting Kubernetes Secrets requires proper RBAC, cluster security and, when appropriate, encryption at rest.

The Secret Structure

FieldPurpose
apiVersionDefines the Kubernetes API version
kindIdentifies the resource as a Secret
metadataContains the Secret name and metadata
typeDescribes the intended Secret format
dataStores base64-encoded values
stringDataAccepts ordinary strings that Kubernetes converts into data

Using stringData

The stringData field allows Secret values to be written as ordinary strings in a manifest. Kubernetes converts these values into the data representation when the Secret is created or updated.

apiVersion: v1
kind: Secret
metadata:
  name: app-credentials
type: Opaque
stringData:
  username: admin
  password: supersecret

stringData is convenient when creating Secrets declaratively because developers do not have to manually encode every value with base64.

⚠️ Using stringData does not make a secret manifest safe to commit to a public repository. The original values are still present in the YAML file and should be protected like any other credential.

Secret Types

Kubernetes supports several built-in Secret types. The type provides information about how the stored data is intended to be used.

TypeTypical Purpose
OpaqueGeneric arbitrary secret data
kubernetes.io/tlsTLS certificate and private key
kubernetes.io/dockerconfigjsonDocker registry authentication
kubernetes.io/basic-authBasic authentication credentials
kubernetes.io/ssh-authSSH authentication data
bootstrap.kubernetes.io/tokenBootstrap token data

Opaque Secrets

Opaque is the default general-purpose Secret type. It can contain arbitrary key-value data such as application passwords, API tokens or database credentials.

apiVersion: v1
kind: Secret
metadata:
  name: database-credentials
type: Opaque
stringData:
  DB_USER: app
  DB_PASSWORD: change-me

TLS Secrets

The kubernetes.io/tls type is commonly used for TLS certificates and their corresponding private keys. Kubernetes expects the standard tls.crt and tls.key data keys.

apiVersion: v1
kind: Secret
metadata:
  name: example-tls
type: kubernetes.io/tls
data:
  tls.crt: BASE64_CERTIFICATE
  tls.key: BASE64_PRIVATE_KEY

Docker Registry Secrets

Kubernetes can use dockerconfigjson Secrets to authenticate with private container registries. These Secrets can then be referenced by Pods when pulling private images.

apiVersion: v1
kind: Secret
metadata:
  name: registry-credentials
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: BASE64_DOCKER_CONFIG

Using a Secret as an Environment Variable

A Pod can expose an individual Secret value as an environment variable using secretKeyRef. This is useful for applications that expect credentials through environment variables.

apiVersion: v1
kind: Pod
metadata:
  name: secret-demo
spec:
  containers:
    - name: app
      image: example/app:1.0
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-credentials
              key: DB_PASSWORD

The container receives DB_PASSWORD from the Secret without requiring the password to appear directly in the Pod specification.

Importing Secret Values with envFrom

When an application needs multiple values from the same Secret, Kubernetes can import all Secret keys as environment variables using envFrom.

containers:
  - name: app
    image: example/app:1.0
    envFrom:
      - secretRef:
          name: database-credentials

Every compatible key in the Secret becomes an environment variable inside the container. Explicit secretKeyRef entries provide more control when only selected values should be exposed.

Mounting Secrets as Files

Secrets can be mounted into containers as volumes. Each key becomes a file and its value becomes the file contents. This is particularly useful for certificates, private keys and applications that read credentials from files.

apiVersion: v1
kind: Pod
metadata:
  name: secret-file-demo
spec:
  containers:
    - name: app
      image: example/app:1.0
      volumeMounts:
        - name: credentials
          mountPath: /etc/app/secrets
          readOnly: true
  volumes:
    - name: credentials
      secret:
        secretName: app-credentials

The Secret values become files inside /etc/app/secrets. Applications can then read those files without receiving the credentials through their command line or application manifest.

💡 Use readOnly mounts for Secret volumes when the application only needs to read credentials. This communicates the intended access pattern and avoids unnecessary write permissions.

Creating Secrets with kubectl

Secrets can be created from literal values, files or TLS certificate pairs using kubectl. This is useful for local development and administrative tasks.

kubectl create secret generic app-credentials \
  --from-literal=username=admin \
  --from-literal=password=supersecret

A file can also be used as the source of a Secret.

kubectl create secret generic app-credentials \
  --from-file=credentials.txt

Creating TLS Secrets

kubectl provides a dedicated command for creating TLS Secrets from an existing certificate and private key.

kubectl create secret tls example-tls \
  --cert=tls.crt \
  --key=tls.key

Secrets with Deployments

Deployments commonly reference Secrets because the Deployment creates the Pods that need access to credentials. The container image remains independent from the environment-specific Secret.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: example/api:1.0
          env:
            - name: DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: database-credentials
                  key: DB_PASSWORD

Secrets and Namespaces

Secrets are namespace-scoped resources. A Pod normally references a Secret from the same namespace, which makes namespaces useful for separating credentials between development, staging and production environments.

metadata:
  name: database-credentials
  namespace: production

Separate Secrets can therefore be maintained for each environment while the application Deployment remains structurally similar.

How Kubernetes Protects Secrets

Kubernetes provides several mechanisms that can help protect Secret data, including RBAC authorization, transport security and optional encryption at rest. The actual security level depends on how the cluster is configured and who has permission to access Secret resources.

ProtectionPurpose
RBACControls which identities can access Secrets
TLSProtects communication with the Kubernetes API
Encryption at restProtects stored Secret data in the backing datastore
Namespace isolationSeparates resources by namespace
⚠️ A Secret is only as secure as the permissions and infrastructure around it. Anyone with sufficient Kubernetes permissions to read Secrets may be able to retrieve their values.

RBAC and Secret Access

Role-Based Access Control determines which users, groups and service accounts can perform operations on Kubernetes resources. Secret access should be restricted to the workloads and administrators that actually need it.

rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]

Granting broad permissions such as unrestricted access to all Secrets increases the potential impact of a compromised account or workload. Least-privilege access is therefore an important part of Secret management.

Encryption at Rest

Kubernetes can be configured to encrypt Secret data at rest in the cluster's backing datastore. This protects stored data if the underlying datastore is accessed, but it does not replace RBAC or other access controls.

💡 For production clusters, review whether encryption at rest is enabled and understand which encryption provider and key-management process your cluster uses.

Secrets in Version Control

Putting real credentials directly into Kubernetes YAML and committing those files to Git can expose secrets to everyone who can access the repository and its history. Removing a secret from the latest commit does not necessarily remove it from Git history.

⚠️ Never commit real passwords, API keys, private keys or production credentials to a public repository. If a credential has already been exposed, treat it as compromised and rotate it.

Secret Management Outside Kubernetes

Larger environments often use external secret-management systems instead of manually maintaining credentials as Kubernetes objects. These systems can provide centralized access control, auditing, rotation and integration with dedicated secret stores.

ApproachTypical Use
Kubernetes SecretSimple cluster-managed credentials
External secret managerCentralized production secret management
Cloud secret serviceManaged credentials integrated with cloud infrastructure

Secret Rotation

Credentials should not remain valid forever. Secret rotation replaces old credentials with new ones to reduce the impact of accidental exposure or compromise.

  • Generate a new credential.
  • Store the new value securely.
  • Update the Kubernetes Secret.
  • Restart or reload workloads when required.
  • Verify that applications use the new credential.
  • Revoke the old credential.

Environment Variables vs Mounted Secret Files

MethodAdvantagesConsiderations
Environment variableSimple and widely supportedCan appear in process-related diagnostics and application environments
Mounted fileWorks well for certificates and file-based credentialsApplication must know where to read the file

Neither method is universally better. The choice depends on the application and the type of credential. File mounts are particularly natural for TLS certificates and private keys, while environment variables are convenient for simple application credentials.

Secret Updates and Running Pods

Updating a Secret does not automatically recreate Pods. When a Secret is consumed as an environment variable, an existing container continues using the value it received when it started.

Mounted Secret volumes can receive updated Secret data, although the application may need to reload the files before the new values are used. Applications that cache credentials may therefore require an explicit restart or reload mechanism.

Common Mistakes

  • Assuming base64 encoding provides encryption.
  • Committing real credentials to Git repositories.
  • Giving users or service accounts unnecessary Secret permissions.
  • Using one credential across unrelated applications.
  • Leaving credentials unchanged for long periods.
  • Assuming Secret updates automatically restart Pods.
  • Storing non-secret application configuration in Secrets instead of ConfigMaps.

Best Practices

  • Use Secrets for sensitive values and ConfigMaps for ordinary configuration.
  • Restrict Secret access with least-privilege RBAC.
  • Enable encryption at rest where appropriate.
  • Use HTTPS for Kubernetes API communication.
  • Avoid committing real credentials to source control.
  • Rotate credentials regularly and after suspected exposure.
  • Use separate credentials for different applications and environments.
  • Prefer external secret-management systems for complex production environments.
  • Use read-only Secret mounts when applications only need to read files.
  • Audit who and which workloads can access sensitive Secrets.
💡 Think of Kubernetes Secrets as one part of a larger secret-management strategy. The Secret object provides a way to deliver sensitive values to workloads, while RBAC, encryption, rotation and external secret-management systems provide additional layers of protection.

Frequently Asked Questions

What is a Kubernetes Secret?

A Kubernetes Secret is an API object used to store sensitive configuration such as passwords, tokens, credentials and certificates so workloads can consume them without embedding them directly into container images.

Are Kubernetes Secrets encrypted?

Secret data is not made secure simply because it is stored as a Secret. Kubernetes can be configured to encrypt Secret data at rest, while RBAC and other controls restrict who can access it.

Is base64 encryption?

No. Base64 is an encoding format. Anyone who obtains a base64-encoded Secret value can decode it easily.

How can a Pod use a Secret?

A Pod can consume Secret values as environment variables, import multiple values with envFrom, or mount Secret data as files through a volume.

Should Secrets be committed to Git?

Real credentials should generally not be committed to Git. Even if a Secret is later deleted, its value may remain in repository history or other copies of the repository.

Do Secret changes restart Pods?

No. Updating a Secret does not automatically restart Pods. Environment variables remain unchanged inside existing containers, while mounted Secret files can be updated and may require application reload logic.

What is the difference between a Secret and a ConfigMap?

ConfigMaps are intended for non-sensitive configuration, while Secrets are intended for sensitive values such as passwords, tokens and certificates.

Helpful Kubernetes Tools

A Kubernetes Secret Generator creates Secret manifests for Kubernetes workloads, a Secret Generator helps produce secret values for development and deployment workflows, an Environment Variable Generator creates environment-variable configuration, a dotenv Encryptor helps protect environment files, and a YAML Formatter makes Kubernetes manifests easier to read and review.

Conclusion

Kubernetes Secrets provide a standard way to deliver sensitive configuration to containers without embedding credentials directly into application images or ordinary Pod configuration. They can be consumed through environment variables or mounted files and support common use cases such as database credentials, API tokens, registry authentication and TLS certificates. However, Secrets should not be confused with encryption or treated as a complete security solution. Strong RBAC, encryption at rest, careful repository practices, credential rotation and appropriate external secret-management systems are all important parts of protecting sensitive Kubernetes data.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.