Pull an image from a private docker registry in Kubernetes Pod
Log in to Docker Hub
In order to pull a image from Docker Hub, you must authenticate with a registry. Use docker tool to log in to the Docker Hub as below. A username and password is needed to log in.
$ docker login
The login process creates or updates the config.json file which holds an authorization token.
$ cat /root/.docker/config.json
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "xxx="
}
}
}
Create a Secret based on existing credentials
A Kubernetes cluster uses the Secret of kubernetes.io/dockerconfigjson type to authenticate with a container registry to pull a private image.
If you already ran docker login, you can copy that credential into Kubernetes:
$ kubectl create secret generic regcred --from-file=.dockerconfigjson=/root/.docker/config.json --type=kubernetes.io/dockerconfigjson
You can inspect the Secret as below.
$ kubectl get secret regcred --output=yaml
apiVersion: v1
data:
.dockerconfigjson: <base64-formatted-docker-credentials>
kind: Secret
metadata:
creationTimestamp: "2022-02-28T22:25:43Z"
name: regcred
namespace: default
resourceVersion: "1503624"
uid: yyy
type: kubernetes.io/dockerconfigjson
The value of the .dockerconfigjson field is a base64 representation of your Docker credentials. To understand what is in the .dockerconfigjson field, convert the secret data to a readable format:
$ kubectl get secret regcred --output="jsonpath={.data.\.dockerconfigjson}" | base64 --decode
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "xxx="
}
}
}
Create a Pod that uses the Secret to pull image
$ vi my-private-reg-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: private-reg
spec:
containers:
- name: private-reg-container
image: <your-private-image>
imagePullSecrets:
- name: regcred
$ kubectl apply -f my-private-reg-pod.yaml
$ kubectl get pod private-reg
Note that the imagePullSecrets field specifies that Kubernetes should get the credentials from a Secret named regcred in order to pull a container image from Docker Hub.