---
title: "Kubernetes Secrets Management: Enhance Safety & Reliability"
description: "Explore expert techniques for securing Kubernetes secrets in production with this guide. Learn to enhance safety and reliability in your Kubernetes deployments."
canonical: "https://adamtheautomator.com/kubernetes-secrets/"
---

# Kubernetes Secrets Management: Enhance Safety & Reliability

> Explore expert techniques for securing Kubernetes secrets in production with this guide. Learn to enhance safety and reliability in your Kubernetes deployments.

Source: https://adamtheautomator.com/kubernetes-secrets/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Kubernetes Secrets Management: Enhance Safety & Reliability](https://adamtheautomator.com/wp-content/uploads/2022/06/How-to-Keep-Kubernetes-Secrets-Safe.jpg)

# Kubernetes Secrets Management: Enhance Safety & Reliability

[![](https://secure.gravatar.com/avatar/9c3cbd45c82cff94f1627c6862c2f3c7425e8c0c9fe804476fbcbad778e178cc?s=192&d=mm&r=g)Muhammed Ali](https://adamtheautomator.com/author/muhammed-ali/)12 December 20236 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Kubernetes](/tag/kubernetes/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating and Loading Kubernetes Secrets](#creating-and-loading-kubernetes-secrets)
*   [Pulling Docker Images Using Secrets](#pulling-docker-images-using-secrets)
*   [Limiting Secret Usage](#limiting-secret-usage)
*   [Conclusion](#conclusion)

If you’ve been using [Kubernetes](https://kubernetes.io/) for a while and want to learn how to securely use your Kubernetes secrets while orchestrating, you’ve come to the right place.

This tutorial is unlike other Kubernetes tutorials that ignore the security aspect. You’ll immerse yourself in learning about securely utilizing your secrets. All while working in a Kubernetes environment.

Get ready to keep your secrets away from prying eyes!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   [Minikube](https://minikube.sigs.k8s.io/docs/start/) [](https://www.youtube.com/watch?v=d6WC5n9G_sM&t=1503s)node created and running on [VirtualBox](https://www.virtualbox.org/) – This tutorial uses Minikube v1.25.2 and VirtualBox 6.1.
    
*   A Linux machine – This tutorial uses Ubuntu 20.04.3 LTS.
    

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   A [Docker Hub account](https://hub.docker.com/) with a private image stored for use.
    
*   Docker is installed on your Linux machine.
    

Related:[How to Install and Use Docker on Ubuntu (In the Real World)](https://adamtheautomator.com/docker-ubuntu/)

## Creating and Loading Kubernetes Secrets

When working with Kubernetes, you may encounter an image that needs to use sensitive environment variables such as API keys and passwords.

For example, when using a MongoDB image, you’ll need credentials to authenticate. Those credentials need to be stored as [secrets](https://kubernetes.io/docs/concepts/configuration/secret/). A secret is a [Kubernetes](https://adamtheautomator.com/mongodb-kubernetes/) object used to handle data like TLS, API keys, tokens, and passwords.

Related:[How To Perform a MongoDB Kubernetes Installation](https://adamtheautomator.com/mongodb-kubernetes/)

To create and load Kubernetes secrets:

1\. Create a new directory (mkdir) named secrets for your project (directory name is arbitrary), and switch (cd) to that directory.

```bash
mkdir secrets
cd secrets
```

2\. Next, run the below [kubectl create secret](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#-em-secret-em-) command to create a secret where:

*   `generic sub-command - Indicates the default [secret type](https://kubernetes.io/docs/concepts/configuration/secret/#secret-types).`
    
*   `mongo-secret - The secret’s name to be referenced.`
    
*   `--from-literal flag - Takes in the secrets as key/value pairs.`
    

```bash
kubectl create secret generic mongo-secret --from-literal=MONGO_INITDB_ROOT_USERNAME=username --from-literal=MONGO_INITDB_ROOT_PASSWORD='hidden-password'
```

![Creating a Secret](https://adamtheautomator.com/wp-content/uploads/2022/06/image-230.png)

Creating a Secret

3\. Next, run the following [kubectl describe](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#describe) command to confirm you’ve successfully created the secret (mongo-secret).

```bash
kubectl describe secret mongo-secret
```

After running the command, you’ll notice the values are concealed since Kubernetes encodes the values in base64.

![Describing mongo-secret Secrets](https://adamtheautomator.com/wp-content/uploads/2022/06/image-231.png)

Describing mongo-secret Secrets

4\. Create a YAML file to the project directory (_secrets_) with your preferred text editor and paste the code below into the YAML file. Name the YAML file as you like, but this tutorial’s choice is _mongo\_deployment.yaml_.

The code below creates a MongoDB container in a pod and uses environment variables from secrets.

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo-deployment
  labels:
    app: mongodb
spec:
  replicas: 1  # State the number of replicas of the application you need.
  selector:
    matchLabels:
      app: mongodb
  template:
    metadata:
      labels:
        app: mongodb
    spec:
      containers:
			  # State the image's name on Docker Hub to build the container from.
      - name: mongodb
        image: mongo
        ports:
				# State container port for Solr server
        - containerPort: 27017
        env:
        - name: MONGO_INITDB_ROOT_USERNAME # required by mongodb image
          valueFrom:
            secretKeyRef:
              name: mongo-secret # name of secret
              key: MONGO_INITDB_ROOT_USERNAME
        - name: MONGO_INITDB_ROOT_PASSWORD 
          valueFrom:
            secretKeyRef:
              name: mongo-secret
              key: MONGO_INITDB_ROOT_PASSWORD 
```

Related:[How to Deploy and Manage a Docker MongoDB Container](https://adamtheautomator.com/docker-mongodb/)

5\. Now, run the [kubectly apply](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#apply) command below to apply the configurations you set in the _mongo\_deployment.yaml_ file.

```bash
kubectl apply -f mongo_deployment.yaml
```

![Applying Configurations from the mongo\_deployment.yaml File](https://adamtheautomator.com/wp-content/uploads/2022/06/image-232.png)

Applying Configurations from the mongo\_deployment.yaml File

6\. Finally, run the command below to get the list of all pods.

```bash
kubectl get pods
```

Below, you can verify the newly-created pod exists and is running.

![Getting All Available Pods](https://adamtheautomator.com/wp-content/uploads/2022/06/image-233.png)

Getting All Available Pods

> _Depending on the speed of your internet and your local machine, containers’ activation in the pods may take five to 10 minutes to complete._

## Pulling Docker Images Using Secrets

When working with a Docker image in a private registry, you must authenticate before you can pull the image. The authentication can be handled by Kubernetes using Docker’s _config.json._

Kubernetes converts Docker’s _config.json_ into a secret, and from there, you can use it in your deployment file. The private registry you will use in this tutorial is Docker Hub.

Related:[How to Convert YAML to JSON \[Python, PowerShell, Go\]](https://adamtheautomator.com/yaml-to-json/)

Pull Docker images from a private registry using secrets with the following steps:

1\. Run the docker login command below to log in to your Docker hub account. Be sure to replace username and password with your Docker Hub credentials.

This command generates a _config.json_ file that holds your authorization token.

```bash
docker login -u username -p password
```

![Logging in to Docker](https://adamtheautomator.com/wp-content/uploads/2022/06/image-234.png)

Logging in to Docker

2\. Next, run the following cat command to check if your authorization token has been generated.

```bash
cat ~/.docker/config.json
```

![Displaying Authentication Token](https://adamtheautomator.com/wp-content/uploads/2022/06/image-235.png)

Displaying Authentication Token

3\. Run the below command to register your Docker auth token (~/.docker/config.json) into Kubernetes in serialized JSON format as a secret with the following:

*   Set the name of the data item to .dockerconfigjson
    
*   SSet the type to kubernetes.io/dockerconfigjson
    
*   Set auth-token as the name that will be used to reference the secret.
    

But be sure to change /home/muhammed/.docker/config.json with the path to your own Docker _config.json_ file.

```bash
kubectl create secret generic auth-token \
    --from-file=.dockerconfigjson=/home/muhammed/.docker/config.json \
    --type=kubernetes.io/dockerconfigjson
```

![Turning Docker Authentication Token Into Secret](https://adamtheautomator.com/wp-content/uploads/2022/06/image-236.png)

Turning Docker Authentication Token Into Secret

4\. Create a new YAML file in your project directory (_secrets_) and populate the code below into the YAML file. Name the YAML file as you like, but the YAML file is named _private\_deployment.yaml_ for this tutorial.

The code below creates a pod with a specified private Docker image. So be sure to replace khabdrick/sample:v1 with your own private Docker image.

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: private-deployment # name of the pod
spec:
  containers:
  - name: example-container
    image: khabdrick/sample:v1 # a private image in Docker Hub
    ports:
      - containerPort: 5000
  imagePullSecrets:
  - name: auth-token
```

Related:[How to Update Docker Images to the Latest Version](https://adamtheautomator.com/update-docker/)

5\. Now, run the command below to apply the configurations you set in the private\_deployment.yaml file.

```bash
kubectl apply -f private_deployment.yaml
```

![Applying Configurations from the private\_deployment.yaml File](https://adamtheautomator.com/wp-content/uploads/2022/06/image-237.png)

Applying Configurations from the _private\_deployment.yaml_ File

6\. Finally, run the command below to see if the pod was created and running as expected.

```bash
kubectl get pods
```

![Getting All Available Pods](https://adamtheautomator.com/wp-content/uploads/2022/06/image-238.png)

Getting All Available Pods

## Limiting Secret Usage

You now have a secret, and you’re one step closer to keeping it safe. As you know, the concept of a secret is keeping it, well, a secret. So limit the secret usage to yourself. How? Set your secrets within a [namespace](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/). When a user is in a particular namespace, that user cannot access secrets from another namespace.

If namespaces are not set, Kubernetes creates one with the name default, so all the secrets you created are in default namespace.

To create secrets that only specific users can access, create a new namespace before creating the secrets:

1\. Create a new YAML file called new-namespace.yaml and add the code below to the YAML file.

The code below creates a namespace called new-namespace, but you change the name as you like.

```bash
apiVersion: v1
kind: Namespace
metadata:
  name: new-namespace # this could be any name of your choice
```

2\. Next, run the kubectl create command to create the namespace by the configuration you set in the new-namespace.yml file.

```bash
kubectl create -f new-namespace.yaml
```

![Creating a New Namespace](https://adamtheautomator.com/wp-content/uploads/2022/06/image-239.png)

Creating a New Namespace

3\. Run the command below to list all namespaces available.

```bash
kubectl get namespace
```

Below, you can verify that the namespace (new-namespace) was created successfully.

![Listing All Namespaces](https://adamtheautomator.com/wp-content/uploads/2022/06/image-240.png)

Listing All Namespaces

4\. Now, run the following command to create a new secret for username and password. But this time, you’ll attach a –namespace tag and define the namespace (new-namespace) where you want to store the new secret.

```bash
kubectl create secret generic new-secret --from-literal=USERNAME=username --from-literal=PASSWORD='password' --namespace=new-namespace
```

![Creating a Secret Within a Namespace](https://adamtheautomator.com/wp-content/uploads/2022/06/image-241.png)

Creating a Secret Within a Namespace

5\. Run the kubectl get secrets command below to try and view all the secrets.

```bash
kubectl get secrets
```

You’ll notice below that the newly-created secret is not on the list since you’re not in the right namespace to access it.

![Viewing Secrets in default Namespace](https://adamtheautomator.com/wp-content/uploads/2022/06/image-242.png)

Viewing Secrets in default Namespace

6\. Finally, run the same kubectl get secrets command. But this time, append the –namespace tag along with the namespace’s name (new-namespace).

```powershell
kubectl get secrets --namespace=new-namespace
```

As you can see below, the newly-created secret (new-secret) now shows in the list since you’re in the correct namespace (new-namespace)

![Viewing Secrets in a Specific Namespace (new-namespace)](https://adamtheautomator.com/wp-content/uploads/2022/06/image-243.png)

Viewing Secrets in a Specific Namespace (new-namespace)

## Conclusion

In this tutorial, you’ve learned the best practices of keeping secrets safe while working in a Kubernetes environment using a MongoDB image as the use case. You went through using Kubernetes to authenticate your Docker registry and fetch a private image.

Now anytime, you can limit secret usage to specific users using namespaces. So spare yourself worrying about your secrets and keep them safe.

Curious to know how to apply your newly-acquired knowledge? Perhaps storing your API keys as secrets instead of `env` files?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fkubernetes-secrets%2F&text=Kubernetes%20Secrets%20Management%3A%20Enhance%20Safety%20%26%20Reliability)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fkubernetes-secrets%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fkubernetes-secrets%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/06/Effortless-Storage-Management-With-Kubernetes-PVC.jpg)

### [Kubernetes PVC for Data Reliability: A Comprehensive Guide](/kubernetes-pvc/)

Tired of Kubernetes storage headaches? Discover how Kubernetes PVC simplifies data persistence and ensures your applications stay up and running.

![](https://adamtheautomator.com/wp-content/uploads/2024/01/kustomize.jpg)

### [A Beginners Guide to Kubernetes Kustomize](/kustomize/)

Dive into Kubernetes Kustomize to master dynamic deployments — A beginner’s guide for personalized configurations and seamless adaptability!

![](https://adamtheautomator.com/wp-content/uploads/2023/11/github-arc.jpg)

### [Using GitHub ARC to run Self-Hosted Runners on Kubernetes](/github-arc/)

Maximize workflow efficiency with GitHub ARC: deploy, configure, and test self-hosted runners on Kubernetes seamlessly in this ATA tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
