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.
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=The Secret Structure
| Field | Purpose |
|---|---|
| apiVersion | Defines the Kubernetes API version |
| kind | Identifies the resource as a Secret |
| metadata | Contains the Secret name and metadata |
| type | Describes the intended Secret format |
| data | Stores base64-encoded values |
| stringData | Accepts 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: supersecretstringData is convenient when creating Secrets declaratively because developers do not have to manually encode every value with base64.
Secret Types
Kubernetes supports several built-in Secret types. The type provides information about how the stored data is intended to be used.
| Type | Typical Purpose |
|---|---|
| Opaque | Generic arbitrary secret data |
| kubernetes.io/tls | TLS certificate and private key |
| kubernetes.io/dockerconfigjson | Docker registry authentication |
| kubernetes.io/basic-auth | Basic authentication credentials |
| kubernetes.io/ssh-auth | SSH authentication data |
| bootstrap.kubernetes.io/token | Bootstrap 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-meTLS 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_KEYDocker 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_CONFIGUsing 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_PASSWORDThe 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-credentialsEvery 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-credentialsThe 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.
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=supersecretA file can also be used as the source of a Secret.
kubectl create secret generic app-credentials \
--from-file=credentials.txtCreating 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.keySecrets 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_PASSWORDSecrets 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: productionSeparate 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.
| Protection | Purpose |
|---|---|
| RBAC | Controls which identities can access Secrets |
| TLS | Protects communication with the Kubernetes API |
| Encryption at rest | Protects stored Secret data in the backing datastore |
| Namespace isolation | Separates resources by namespace |
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.
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.
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.
| Approach | Typical Use |
|---|---|
| Kubernetes Secret | Simple cluster-managed credentials |
| External secret manager | Centralized production secret management |
| Cloud secret service | Managed 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
| Method | Advantages | Considerations |
|---|---|---|
| Environment variable | Simple and widely supported | Can appear in process-related diagnostics and application environments |
| Mounted file | Works well for certificates and file-based credentials | Application 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.
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.