Kubernetes setup Dockerhub secret
When a Kubernete’s pod or deployment pull the container image, the easiest way is to host the image in Dockerhub. However, sometimes you need to host the image in a private registry, therefore, you need to create a secret in Kubernetes to store the credentials and enable the pod to pull the image from the private registry.
Step 1: Create a secret
Using the kubectl command, create a secret as follows:
kubectl create secret generic dockerhub \
--from-file=.dockerconfigjson=~/.docker/config.json \
--type=kubernetes.io/dockerconfigjson
The create secret
command creates a secret with the name dockerhub
and the type kubernetes.io/dockerconfigjson
. The --from-file
flag specifies that the secret should be created from the file .dockerconfigjson
in the home directory of the user, and, the kubernetes.io/dockerconfigjson
type is used to specify that the secret is in the format of a Docker configuration file.
Step 2: Specify the secret in the Pod definition
In the spec section of the Pod definition, add the following lines:
imagePullSecrets:
- name: dockerhub
The imagePullSecrets
field specifies that the pod should use the secret to pull the image from the private registry. The name
field specifies the name of the secret. A complete example of the Pod definition is shown below:
---
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: my-app-container
image: my-docker-hub-user/my-app-image
imagePullSecrets:
- name: dockerhub
Step 3: Deploy the Pod
The Pod is now ready to be deployed in the Kubernetes cluster using the private image.
kubectl apply -f my-app.yaml