Almost every software application has some secret data. This can range from database credentials to TLS certificates or access tokens to establish secure connections.
The platform you build your application on should provide a secure means for managing this secret data. This is why Kubernetes provides an object called a Secret to store sensitive data you might otherwise put in a Pod specification or your application container image.
What are secrets in Kubernetes?
Kubernetes Secrets are objects used to store and manage sensitive information such as passwords, OAuth tokens, SSH keys, and API keys. The primary purpose of Secrets is to reduce the risk of exposing sensitive data while deploying applications on Kubernetes.
Instead of embedding sensitive data directly within Pods or configuration files, which could expose it to a wider audience than intended, Secrets allow Kubernetes to store and use sensitive data in a more secure and manageable way.
Are Kubernetes secrets secure?
While Kubernetes Secrets offer better security than storing sensitive data in ConfigMaps, they are not inherently highly secure by default. Kubernetes Secrets are base64-encoded and can be accessed through RBAC controls, mounted as volumes, or exposed as environment variables.
However, their biggest vulnerability is that they are stored in plaintext within etcd by default. To mitigate this risk, you must enable encryption at rest in the kube-apiserver. Additionally, improper RBAC configurations can lead to secret leaks, potentially causing downtime, performance degradation, and customer dissatisfaction.
For enhanced security, consider using an external secrets management service like HashiCorp Vault or AWS Secrets Manager. These solutions offer features such as automated secret rotation and stronger encryption, reducing the risk of exposure.
Using A Kubernetes Secret
Secrets can be consumed by Pods as environment variables or mounted volumes, and can also be used directly by system components without exposing them to Pods. A common example is storing credentials for external systems.
The secret volume sources are validated to ensure that the specific object’s reference actually points to an object of a particular object of secret type. Due to this, the secret should be created before any pods that depend on it. If the required secret cannot be fetched due to its non-existence or due to the temporary lack of connection to the AOI server the kubelet periodically retires running that specific Pod. Kubelet also reports the event for that Pod including all the details of the problems fetching the secret.
When defining environment variables from Secrets, they are required by default. Pods will not start until all non-optional Secrets are available. You can mark them as optional, but if a Pod references a missing key in a Secret, startup will fail.
Kubernetes Secret Visible to One Container in a Pod
- Sensitive information in a Pod can be restricted to only the container that needs it.
- Example scenario:
- Frontend container → handles user interaction and business logic.
- Backend (signer) container → responsible for message signing.
- The signer container requires access to a private key stored in a Kubernetes Secret.
- The frontend container does not need access to this secret.
- By mounting the secret only in the signer container:
- The signer has secure access to
.private-key. - The frontend is fully isolated from sensitive data.
- The signer has secure access to
- This setup ensures least privilege access within the Pod.
apiVersion: v1
kind: Secret
metadata:
name: signing-secret
type: Opaque
stringData:
.private-key: password
---
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
containers:
- name: frontend-container
image: myregistry.io/frontend-app
# Frontend does NOT get secret access
- name: signer-container
image: myregistry.io/signer-app
command: ["ls", "-la", "/etc/signing"]
volumeMounts:
- name: signing-volume
readOnly: true
mountPath: "/etc/signing" # Only signer sees the secret
volumes:
- name: signing-volume
secret:
secretName: signing-secret
1. Opaque Secrets
These are the default secret types i.e., if don’t specify any type while creating, this Opaque secrets type is used default. It is used for storing general user-defined data values. We have to generic as subcommand to use this type, if want to specify. The following is an empty
Example:
Let’s add the following secret to our Kubernetes cluster: “my-awesome-password”. We’ve defined a K8s manifest for creating this secret:
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
password: my-awesome-password
kubectl apply -f secret.yaml
Error from server (BadRequest): error when creating "secret.yaml": Secret in version "v1" cannot be handled as a Secret: illegal base64 data at input byte 2As you can see, we cannot create the secret in our cluster directly, as we need to first base64 encode it. Let’s do that before adding the password there. I will show you how to do it for Linux and MacOS:
echo -n "my-awesome-password" | base64
bXktYXdlc29tZS1wYXNzd29yZA==Now, we will replace the text in our Secret with its base64 option:
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
password: bXktYXdlc29tZS1wYXNzd29yZA==kubectl apply -f secret.yaml
secret/my-secret createdWe can get the Secret from Kubernetes by running the following command:
kubectl get secret my-secret -o jsonpath='{.data.password}'
bXktYXdlc29tZS1wYXNzd29yZA==%To decode the Secret, we can easily use base64 again:
kubectl get secret my-secret -o jsonpath='{.data.password}' | base64 --decode
my-awesome-password%If you don’t want to encode the data manually as shown before, you have an alternative, by creating the secret imperatively:
kubectl create secret generic my-other-secret --from-literal=password=secret
secret/my-other-secret createdTo get the base64 encoded value, we can run:
kubectl get secret my-other-secret -o jsonpath='{.data.password}'
c2VjcmV0%Also, to get the decoded value, we can run:
kubectl get secret my-other-secret -o jsonpath='{.data.password}' | base64 --decode
secret%2. ServiceAccount Token Secrets
This type of secret type is used to identify the serviceAccount It is used for storing credentials that are used by pods to authenitcate with the kubernetes API Server.
Example: Used for storing Access Tokens for communicating with kubernetes resources.
The following yaml code illustrates it clearly:
apiVersion: v1
kind: Secret
metadata:
name: sa-token-secret
annotations:
kubernetes.io/service-account.name: "sa-name"
type: kubernetes.io/service-account-token
3.Docker Config Secrets
It used for serializing the docker configuration files that are used for authenticating with docker registries.
Example: Used for storing credentials for accessing private docker repositories.
The following yaml code helps in you better understanding of docker config secrets:
apiVersion: v1
kind: Secret
metadata:
name: docker-config-secret
type: kubernetes.io/dockerconfigjson
stringData:
.dockerconfigjson: |
{
"auths": {
"https://index.docker.io/v1/": {
"username": "my-username",
"password": "my-password",
"auth": "bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="
}
}
}
4. Basic Authentication Secrets
It is used for storing credentials of basic HTTP authentication. The following yaml code illustrates you clearly about creating basic Authentication secrets types with yaml code:
Example: It is used for storing Username and Password for accessing a web service.
apiVersion: v1
kind: Secret
metadata:
name: basic-auth-secret
type: kubernetes.io/basic-auth
stringData:
username: myuser
password: mypassword
5. SSH Authentication Secrets
It is used for storing credentials for SSH Authentication.The following yaml code helps you in better understanding the ssh Authentication secrets creation.
Example: Used for storing Username and passwords for accessing a web service.
apiVersion: v1
kind: Secret
metadata:
name: ssh-auth-secret
type: kubernetes.io/ssh-auth
stringData:
ssh-privatekey: |
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA7xyzasv..
-----END RSA PRIVATE KEY-----
Using the SSH Secret in a Pod
apiVersion: v1
kind: Pod
metadata:
name: ssh-pod
spec:
containers:
- name: my-container
image: busybox
command: ["cat", "/etc/ssh/ssh-privatekey"]
volumeMounts:
- name: ssh-volume
mountPath: "/etc/ssh"
readOnly: true
volumes:
- name: ssh-volume
secret:
secretName: ssh-auth-secret
6. TLS Secrets
It is used for storing data that is used for TLS encryption and decryption. The following yaml code helps you in better understanding of creating TLS secrets type:
Example: Stores TLS certificates and keys for securing communication between services.
apiVersion: v1
kind: Secret
metadata:
name: tls-secret
type: kubernetes.io/tls
stringData:
tls.crt: |
-----BEGIN CERTIFICATE-----
MIIC+zCCAeOgAwIBAgIJAK6EXAMPLECERTIFICATE
-----END CERTIFICATE-----
tls.key: |
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCEXAMPLEPRIVATEKEY
-----END PRIVATE KEY-----
Using in a Pod:
apiVersion: v1
kind: Pod
metadata:
name: tls-pod
spec:
containers:
- name: nginx-container
image: nginx
volumeMounts:
- name: tls-volume
mountPath: "/etc/tls"
readOnly: true
volumes:
- name: tls-volume
secret:
secretName: tls-secret
7. BootStrap Token Secrets
This secret type is used for storing tokens that are used during the node bootstrap process to sign. The following yaml code helps in understanding and creating the bootstrap token secrets:
apiVersion: v1
kind: Secret
metadata:
name: bootstrap-token-abcdef
namespace: kube-system
type: bootstrap.kubernetes.io/token
stringData:
description: "Bootstrap token for joining nodes"
token-id: abcdef
token-secret: 0123456789abcdef
usage-bootstrap-authentication: "true"
usage-bootstrap-signing: "true"
Ways To Create Kubernetes Secrets
When we working with kubernetes, the management of passwords, tokens and certificaties are important. Kubernetes comes up with multi mode of solutions for securly store and access the data. Here, lets discuss the 3 general methods for creating kubernetes secrets.
1. Create kubernetes secrets using kubectl
2. Create kubernetes secrets using A manifest file
3. Create kubernetes secrets using A Generator like Kustomize
1. Creating Kubernetes Secrets Using Kubectl
It is a quick and straightforward way of creating kubernetes secrets from command line. It is suitable for creating secrets on the fly during development or testing phases.
In this secrets creation, it supports accessing data from literals, files offering flexibility of handling sensitive data. The following command is used for creating secrets with string literals:
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=secretpassword
The following command is used for creating secrets from one or more files:
kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa
2. Create Kubernetes Secrets Using A Manifest File
It comes with facilitating a declarative way of defining secrets using YAML or JSON manifest files. It facilitates with easy sharing and replication of secrets configurations on different environments.
The following is the simple Yaml file for creating kubernetes secrets.
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
username: YWRtaW4= # base64 encoded username
password: cGFzc3dvcmQ= # base64 encoded password
After the saving the above file code as mysecret-file.yaml execute the file and create secrets using following command:
kubectl apply -f mysecret-file.yaml
3. Create Kubernetes Secrets Using A Generator Like Kustomize
This type of method supports seamless integration with Kustomize ( a K8s native configuration management tool ). It facilitates with generating and customizing secrets dynamically based on overlays or patches.
It offers enhanced flexibility and scalability for managing complex secret configurations across mutliple developments.
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
api-key: <base64-encoded-api-key>
After saving the above code file as base-secret.yaml and then execute it with following command:
kustomize build overlays/ | kubectl apply -f -
Kubernetes Secrets vs Configmap
The following are the differences between Kubernetes Secrets and Kubernetes Configmap:
| Features | Kubernetes Secrets | Kubernetes ConfigMaps |
|---|---|---|
| Data Senstivity | It is used for storing sensitive data such as passwords, tokens and certificates | It is suitable for storing non-sensitive configuration data like application settings, environment variables and configuration files. |
| Data Encoding | The data stored in it, is encoded in base64 for having basic security. But its not encryption. | Here the data is stored in plain text without any encoding or encryption. |
| Access Control | It supports RBAC (Role Based Access Control ) for fine grained access control. | Here the access control is limited to namespace-level with controlablility. |
| Use Cases | It is used for storing sensitive and confidential data that is required to store in applications (running pods.) | It is used for storing configuration data that needed to expose for pods as environmental variables or as mounted files. |
| Data Storage | It stores the data securly within the kubernetes cluster. | It stores Alongside of kubernetes resources within the etcd data store. |
How to Manage Kubernetes Secrets?
Management of kubernetes secrets involves steps for securly handing sensitive data within the kubernetes cluster. Some of the managing kubernetes secrets are discussed as follows:
Creation: On using kubectl commands create secrets for storing sentive data such as passwords, tokens or certificates.
Access Control: Implement Role Based Access Control ( RBAC ) to restrict the access of secrets based on users.
Encryption: Consider on using external solutions like Hashicorp Vault for enhancing security of secret data at rest and in transit.
Rotation: Regularly rotating the secrets helps in minimizing the risk of unauthorization and maintaining the security policies.
Alternatives to Kubernetes Secrets
If there is a need to protect your data then secret is not the only option available. There are some other alternatives available.
We can use ServiceAccount and its tokens to identify the cluster if the cloud native component has the need for authentication to another application that is also running within the same Kubernetes Cluster.
We can use third-party tools that can be run by us either outside or from within the cluster that provides secrets management.
If we need authentication we can implement a custom signer for X.509 certificates and then use CertificateSigningRequests to let that custom signer issue certificates to Pods that required them.
We can use a device plugin to expose node local encryption hardware to a specific Pod.
Common interview Questions
1. What is a Kubernetes Secret, and why is it important?
Answer:
A Kubernetes Secret is an object that stores sensitive data like passwords, tokens, or keys. It allows you to separate confidential data from application code. Using Secrets reduces the risk of exposing sensitive data, provides secure access to Pods, and ensures least-privilege access within a cluster.
2. How can you use a Secret in a Pod?
Answer:
You can consume Secrets in a Pod in three main ways:
- Environment variables – inject keys or tokens directly as env vars.
- Mounted volumes – mount the Secret as files inside the container.
- Direct use by system components – e.g., service accounts or controllers that need access to credentials.
3. Can all containers in a Pod access the same Secret?
Answer:
No. You can mount a Secret only in the containers that need it. For example, in a Pod with a frontend and a signer container, only the signer container can access the private key stored in a Secret, ensuring least-privilege access.
4. What are the types of Kubernetes Secrets?
Answer:
- Opaque – default type for storing user-defined data.
- kubernetes.io/service-account-token – stores service account tokens.
- kubernetes.io/dockercfg / dockerconfigjson – stores Docker registry credentials.
- kubernetes.io/basic-auth – stores basic HTTP authentication credentials.
- kubernetes.io/ssh-auth – stores SSH keys.
- kubernetes.io/tls – stores TLS certificates and keys.
- bootstrap.kubernetes.io/token – stores bootstrap tokens for node joining.
5. How do you create a Kubernetes Secret using kubectl?
Answer:
You can create Secrets using literals or files:
From literals:
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=secretpassword
From files:
kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa
6. How do you create a Secret using a manifest file?
Answer:
Create a YAML file with apiVersion: v1, kind: Secret, and type Opaque or any other type. Include your data base64-encoded:
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
username: YWRtaW4= # base64 encoded
password: cGFzc3dvcmQ= # base64 encoded
Apply it using:
kubectl apply -f mysecret-file.yaml
7. What is the purpose of dotfiles in Secrets?
Answer:
Dotfiles (hidden files starting with .) inside Secrets can store sensitive keys or API tokens securely. When mounted in a container, only authorized processes can access them, increasing data confidentiality.
8. How do you manage access control for Kubernetes Secrets?
Answer:
Use RBAC (Role-Based Access Control) to restrict who can view or modify Secrets. Combine this with encryption at rest and optionally tools like HashiCorp Vault for enhanced security. Only authorized users or service accounts can access Secrets in the cluster.
9. What are some alternatives to Kubernetes Secrets?
Answer:
- ServiceAccounts with tokens – for authentication within the cluster.
- Third-party secret management tools – e.g., Vault, AWS Secrets Manager.
- Custom certificate signing – using CertificateSigningRequests (CSRs).
- Device plugins – expose local encryption hardware to Pods for storing sensitive data.
Conclusion
Kubernetes Secrets provide a secure and flexible way to manage sensitive data, such as passwords, API keys, tokens, and certificates, within a Kubernetes cluster. By separating confidential information from application code, Secrets help maintain security, simplify deployments, and enforce least-privilege access for containers.
With multiple ways to create Secrets—using kubectl, manifest files, or tools like Kustomize—teams can choose the approach that best fits their workflow and environment. Proper management, including access control, encryption, and regular rotation, ensures that sensitive data remains protected.
While Secrets enhance security, organizations can also explore alternatives like ServiceAccount tokens, third-party secret management tools, and certificate-based authentication for specialized use cases. By leveraging Kubernetes Secrets effectively, teams can build robust, secure, and scalable containerized applications without compromising operational efficiency.

