Introduction
Previously, I used to create a Secret in each namespace and manually reference it in the Pod’s spec.imagePullSecrets
field to enable pulling images from a private registry. Later, I discovered that you can specify the Secret in the imagePullSecrets
field of a ServiceAccount (such as the default ServiceAccount). As long as the Pod uses this ServiceAccount (and does not specify imagePullSecrets
in its own spec), it will automatically use the credentials specified to pull private images. This means you no longer need to set imagePullSecrets
in every Pod spec, making centralized management much easier. In other words, if you add imagePullSecrets
to the default ServiceAccount, all Pods using the default ServiceAccount will automatically use this Secret to pull private images. By default, Pods use the default ServiceAccount unless another ServiceAccount is explicitly specified, so they will automatically use the imagePullSecrets
from the default ServiceAccount.
Steps
Create the Secret:
kubectl create secret docker-registry my-registry-secret \
--docker-server=<your-registry-server> \
--docker-username=<your-username> \
--docker-password=<your-password>
Add the Secret to the imagePullSecrets
field of the default ServiceAccount:
kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "my-registry-secret"}]}'
Verification
You can check whether the Secret has been successfully added to the default ServiceAccount’s imagePullSecrets
with the following command:
kubectl get serviceaccount default -o jsonpath='{.imagePullSecrets}'
Create a Pod to verify if it can successfully pull the private image:
apiVersion: v1
kind: Pod
metadata:
name: my-private-pod
spec:
containers:
- name: my-container
image: <your-private-image>
If the Pod is created and runs successfully, it means you can now pull private images using the imagePullSecrets
of the default ServiceAccount.
Feel free to follow my blog at www.bboy.app
Have Fun