How To Use Kubernetes Secrets As Files In Containers ?
Last Updated :
15 Mar, 2024
Secrets are Objects in Kubernetes that are used to store the data and credentials that we would not want to share with others. Secret is a Kubernetes component just like Configmap but the difference is that it's used to store secret data credentials and it stores this data not a plain text format but in base64 encoded format. In this article, we will see a brief introduction to Kubernetes Secrets and a tutorial on How to use Kubernetes Secrets as files in containers.
Kubernetes Secrets
A Secret is a Kubernetes Object used to store sensitive data such as passwords, tokens, keys, etc. which we would not want anyone else to access. Using a Secret ensures that we are not including any confidential data in our application code. Secret is a Kubernetes component just like Configmap but the difference is that it's used to store secret data credentials and it stores this data not a plain text format but in base64 encoded format.
Here is a sample Kubernetes Secret:
apiVersion: v1
kind: Secret
metadata:
name: dotfile-secret
data:
.secret-file: dmFsdWUtMg0KDQo=
---
apiVersion: v1
kind: Pod
metadata:
name: secret-dotfiles-pod
spec:
volumes:
- name: secret-volume
secret:
secretName: dotfile-secret
containers:
- name: dotfile-test-container
image: registry.k8s.io/busybox
command:
- ls
- "-l"
- "/etc/secret-volume"
volumeMounts:
- name: secret-volume
readOnly: true
mountPath: "/etc/secret-volume"
Why do we need Secrets?
Role of Secret is similar to that of a Configmap, like Config Map usually contains configuration data like URLs of database or URLs of some other services, Secret is used to store the data and credentials that we would not want to share with others.

In the diagram above, database Username and Password can also be part of the external configuration but putting a password or other credentials in a Config Map in plain text format is firstly insecure and not a good practice. For this purpose Kubernetes has the component called Secret. The passwords, certificates, etc. that you don't want other people to have access to would go in the Secret. Just like Config Map you can just connect it to your Pod so that the Pod can actually see those data and read from the Secret.
Tutorial - How to use Kubernetes Secret as file
In this tutorial we will see how to use Secrets as files within the containers.
Step 1: Creating a Kubernetes Cluster.
You can skip this step if you already have a Kubernetes Cluster running in your machine. But in case you don't have a Cluster running enter the following command to create Kubernetes locally using Minikube:
minikube start

Minikube is a one-node Kubernetes cluster where master processes and work processes both run on one node.
Step 2: Creating a Secret from files
Now let us create two files that will store our two Secrets - username Secret and password Secret. Enter the following command to create two new files in the same directory and add 'shubham' and 'myPassword' as text to those files:
echo -n 'shubham' > ./username.txt
echo -n 'myPassword' > ./password.txt
Now if we check the list of files, we will get our username.txt and password.txt:

Now enter the following command to create a Secret that reads the content from username.txt and password.txtand store them as key value pairs in the Secret:
kubectl create secret generic my-secret \
--from-file=username=./username.txt \
--from-file=password=./password.txt

Step 3: Checking and describing our Secret
Let us check the list of Secrets in our cluster by the following command:
kubectl get secrets
And we can find our my-secret in the list:

We can also get additional information about our Secret object by entering the following command:
kubectl describe secret my-secret

When we how a configuration file of our Secret would look like by entering the following command:
kubectl get secret -o yaml
We will see that the data we created, username and password are now base64 encoded:

Step 4: Deploying a PersistentVolume and PersistentVolumeClaim to the Cluster
We will create a MySQL application in this tutorial that will use Secret as a file, for a MySQL database we will need PersistentVolume in order to store our data and that storage must be requested through a PersistentVolumeClaim. And for that we need to create a file named storage-file.yaml and enter the following code inside it:
apiVersion: v1
kind: PersistentVolume
metadata:
name: mysql-pv-volume
labels:
type: local
spec:
storageClassName: manual
capacity:
storage: 20Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pv-claim
spec:
storageClassName: manual
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
Now we can apply this configuration file to create a PersistentVolume and PersistentVolumeClaim in the cluster using the following command:
kubectl apply -f storage-file.yaml
You will be a similar output and the PersistentVolume and PersistentVolumeClaim will be created:

Step 5: Creating a Deployment that will consume our Secret
Now that our PersistentVolume and PersistentVolumeClaim has been setup, let's create a Deployment that will use our Secret. Create a file named app.yaml and enter the following code inside it:
apiVersion: apps/v1
kind: Deployment
metadata:
name: mysql
spec:
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:latest
env:
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: my-secret
key: username
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
ports:
- containerPort: 3306
volumeMounts:
- name: mysql-persistent-storage
mountPath: /var/lib/mysql
volumes:
- name: mysql-persistent-storage
emptyDir: {}
Have a look at the environment variables we are using in this file:
env:
- name: MYSQL_USER
valueFrom:
secretKeyRef:
name: my-secret
key: username
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
We are using our Secret my-secret to get the value for MYSQL_USER and MYSQL_ROOT_PASSWORD. the username field in my-secret is the value for MYSQL_USER and similarly the password field in my-secret is the value for MYSQL_ROOT_PASSWORD.
Now create a Deployment using this configuration file by entering the following command:
kubectl apply -f app.yaml
You will be a similar output and the Deployment will be created:

Step 6: Confirming that Secrets were used as files in the Container
Now we have setup all the components in the cluster, we have our PersistentVolume and PersistentVolumeClaim for the database and a my-sql Deployment for running Pods in the cluster. We will now confirm that the Pod is using our Secret and for that we will need the name of the Pod. Let us check the list of Pods in the cluster using the following command:
kubectl get pods
Copy the Pod name from here:

My Pod name is mysql-7b4ff4bd5c-rltj6, let us enter the container to see if the environment variables are using the value from Secret or not. Enter the following command for entering the Container and see the environment variables.
kubectl exec -it mysql-7b4ff4bd5c-rltj6 -- env
We will get the list of environment variables in the Container. we can clearly see that environment variables MYSQL_USER and MYSQL_ROOT_PASSWORD have the value "shubham" and "myPassword" that we set in our Secret:

And hence it is confirmed that the Secrets are been used by the containers. Pat yourself on the back because we have finally created Secrets and used them as files in the Container. This is the end of the tutorial on How to use Kubernetes Secrets as files in Containers.
Commands related to Kubernetes Secrets
Enter the command to create a Secrets using --from-literal flag:
kubectl create secret generic [NAME] --from-literal=username=myName --from-literal=password=myPassword
Enter the command to creating a Secret from a configuration file:
kubectl apply -f [SECRET_FILE_NAME]
Enter the command to get the list of Secrets in the cluster:
kubectl get secrets
Enter the command to get additional information about a Secret:
kubectl describe secret [NAME]
Enter the command to delete a Secret:
kubectl delete secret [NAME]
Conclusion
A Secret is a Kubernetes Object used to store sensitive data such as passwords, tokens, keys, etc. which we would not want anyone else to access. Using a Secret ensures that we are not including any confidential data in our application code. Role of Secret is similar to that of a Configmap, like Config Map usually contains configuration data like URLs of database or URLs of some other services, Secret is used to store the data and credentials that we would not want to share with others. We hope that this article taught you about How to use Kubernetes secrets as files in containers. Make sure to follow other articles on GeeksforGeeks to know about more tools in DevOps.
Similar Reads
How to Restart Container in Kubernetes?
Kubernetes is a platform for container orchestration created to simplify application deployment, scaling, and administration. Suppose you have a big package of LEGO parts and you want to use them to make something very spectacular. But as your LEGO creation becomes larger, it becomes harder to organ
8 min read
How to Run Shell Commands in Kubernetes Pods or Containers
In Kubernetes, we create pods by adding an extra layer of information on containers. This Kubernetes in short is known as K8s, an open-source container orchestration tool developed by Google. It is used to orchestrate the containers for bringing Agility in software deployment through scaling, and ma
6 min read
How To Share Storage Between Containers In Kubernetes ?
Kubernetes, or K8s, is an open-sourced container orchestration technology that is used to automate the manual processes of deploying, managing, and scaling applications by the help of containers. Kubernetes uses a single container per pod, which is great for most stateless applications, but some app
7 min read
How To Use Kind To Deploy Kubernetes Clusters?
Kind also referred to as Kubernetes in Docker is a popular open-source tool used for running a Kubernetes cluster locally. Kind uses Docker containers as Cluster Nodes making it substantially faster than its alternatives like Minikube or Docker Desktop which uses a Virtual Machine. Kind is commonly
10 min read
How to Use Kubernetes Annotations?
Annotations are key-value pairs that are used to attach non-identifying metadata to Kubernetes objects. Various tools that are built over Kubernetes use this metadata attached by annotations to perform actions or enhance resource management. Labels and Annotations are used to attach metadata to Kube
11 min read
How to Secure Your Kubernetes Cluster
Kubernetes has become the key factor for well-known container orchestration, allowing agencies to set up and control packages at scale. However, as with all effective devices, security is a paramount problem. Securing your Kubernetes cluster is critical to shield your applications, data, and infrast
15+ min read
How To Use SSH Keys Inside Docker Container?
SSH key is a credential used for remote access of servers without using any type of username and password and Docker is a containerization tool used to encapsulate the application with its dependencies into compact units called docker containers. In this guide, I will first discuss what is SSH key a
5 min read
How to Change Namespace in Kubernetes ?
Kubernetes namespaces offer an indispensable instrument for resource organization and isolation in the ever-changing realm of container orchestration. Like distinct districts in a busy metropolis, each namespace in your Kubernetes cluster serves as a dedicated place where you may organize related st
4 min read
How To Use Kubernetes Labels and Selectors?
Kubernetes (also known as K8s) is an open-source Container Management tool. It helps us automate all the processes like deployment, load balancing, rolling update, etc. We can basically deploy, scale, and manage containerized applications. In Kubernetes, labels and selectors provide a flexible and e
7 min read
How To Set Up Master-Slave Architecture Locally in Kubernetes?
Pre-requisite: Kubernetes Kubernetes is an open-source container orchestration system for automating containerized applications' deployment, scaling, and management. It was originally designed by Google and is now maintained by the Cloud Native Computing Foundation (CNCF). Kubernetes helps you deplo
5 min read