Skip to content
LF Cert Trainer

Lesson 84 · Section 7: Security

Lesson 84: Image security: private registries and image pull secrets

What an image name really points to, how a node logs in to a private registry with an image pull secret, how a ServiceAccount hands that secret to every Pod, and how to read and fix ErrImagePull and ImagePullBackOff. · 16 min read · 4 min video

1/10Image security
0:00 / 3:45

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

What image security is about

A Pod is only as trustworthy as the image it runs. Two questions decide that:

  1. Where does the image come from? The image name answers this. It names a registry, a repository inside it, and one version of the image.
  2. Is the node allowed to fetch it? Public images need no login. Images in a private registry do, and the cluster has to hold that login somewhere safe and present it at the right moment.

For the CKA exam the second question is the practical one. You must be able to create an image pull secret, attach it to a Pod or to a ServiceAccount, and repair a Pod that is stuck in ImagePullBackOff. This lesson also shows how to pin an exact image version, because "which image did I actually run?" is part of the same topic.

How it works

Reading an image name

What the short name nginx really meansno host givenexpandsno tag givenimage: nginxwhat you wrotedocker.ioregistry (default)library/nginxaccount / repository:latesttag (default)Full referencedocker.io/library/nginx:latest
What the short name nginx really means. An image name has up to four parts. Leave one out and the container runtime fills in a default: Docker Hub, the library account, and the tag latest.

Parts:

  • image: nginx (what you wrote)
  • docker.io (registry (default))
  • library/nginx (account / repository)
  • :latest (tag (default))
  • Full reference (docker.io/library/nginx:latest)

Connections:

  • image: nginx to docker.io: no host given
  • image: nginx to library/nginx: expands
  • image: nginx to :latest: no tag given
  • docker.io to Full reference
  • library/nginx to Full reference
  • :latest to Full reference

A full image reference has this shape:

registry.example.com:5000/shop/api:2.4
└────────┬──────────────┘ └──┬───┘ └┬┘
     registry host       repository  tag
PartExampleIf you leave it out
Registry host (and optional port)registry.example.com:5000Docker Hub, docker.io
Repository pathshop/apiA single name such as nginx on Docker Hub becomes library/nginx
Tag:2.4:latest
Digest (instead of a tag)@sha256:4f5c…The tag is used

So image: nginx means docker.io/library/nginx:latest, and image: bitnami/kubectl means docker.io/bitnami/kubectl:latest. The library account holds Docker Hub's official images. Other public registries you will meet are registry.k8s.io (the Kubernetes components themselves), quay.io, ghcr.io and the registries of the cloud providers.

The first part of a name counts as a registry host only when it contains a dot or a colon, or is localhost. That is why shop/api is read as "account shop on Docker Hub", while registry.example.com/shop/api is read as "repository shop/api on registry.example.com".

A tag can move; a digest cannot. A tag is a label that the image's publisher can point at a new image at any time. nginx:1.29 today and nginx:1.29 next month may be different files. A digest is the hash of the image content, so nginx@sha256:… always means exactly the same image. latest is not special: it is an ordinary tag that happens to be the default, and it does not mean "newest".

Why a private image fails without a login

When the kubelet starts a container it asks the container runtime (containerd on most clusters) to pull the image. The runtime contacts the registry. For a private repository the registry answers "not authorised", the pull fails, and the Pod reports it in two steps:

  • ErrImagePull: the pull was tried and failed.
  • ImagePullBackOff: the kubelet is waiting before the next try. The wait doubles after each failure, up to five minutes.

Neither status tells you the cause. The cause is in the Pod's events:

Events:
  Type     Reason   From     Message
  Normal   Pulling  kubelet  Pulling image "registry.example.com/shop/api:2.4"
  Warning  Failed   kubelet  Failed to pull image "registry.example.com/shop/api:2.4": failed to resolve
                             reference "registry.example.com/shop/api:2.4": pull access denied, repository
                             does not exist or may require authorization
  Warning  Failed   kubelet  Error: ErrImagePull
  Normal   BackOff  kubelet  Back-off pulling image "registry.example.com/shop/api:2.4"
  Warning  Failed   kubelet  Error: ImagePullBackOff

Notice that the registry does not say whether the repository is missing or merely private. That is deliberate: a registry should not reveal which private repositories exist. You have to work out which case you are in.

The image pull secret

With Docker on your laptop you would run docker login registry.example.com once, and Docker would save the login in ~/.docker/config.json. Kubernetes stores the same file content in a Secret of type kubernetes.io/dockerconfigjson. The Secret has one key, .dockerconfigjson, and its decoded value looks like this:

{
  "auths": {
    "registry.example.com": {
      "username": "deploy",
      "password": "S3cret!",
      "auth": "ZGVwbG95OlMzY3JldCE="
    }
  }
}

The key under auths is the registry host. The kubelet uses a login only for images whose name starts with that host, so a Secret for registry.example.com does nothing for an image on ghcr.io. The auth value is username:password in base64. Like every Secret, this is encoded, not encrypted: anyone who may read the Secret may read the password.

You do not write this JSON by hand. kubectl create secret docker-registry builds it from three flags.

From Secret to pulled image

How a private image reaches the nodecreatenamesassigned to nodeCRIloginYoucreate the SecretSecret regcreddockerconfigjsonPod apiimagePullSecretskubeletreads the Secretcontainerdpulls with the loginPrivate registryregistry.example.com
How a private image reaches the node. The login is stored as a Secret. The Pod names it, the kubelet reads it and passes the username and password to the container runtime, and the runtime presents them to the registry.

Parts:

  • You (create the Secret)
  • Secret regcred (dockerconfigjson)
  • Pod api (imagePullSecrets)
  • kubelet (reads the Secret)
  • containerd (pulls with the login)
  • Private registry (registry.example.com)

Connections:

  • You to Secret regcred: create
  • Pod api to Secret regcred: names
  • Pod api to kubelet: assigned to node
  • kubelet to containerd: CRI
  • containerd to Private registry: login
  1. You create the Secret in the Pod's namespace.
  2. The Pod lists it under spec.imagePullSecrets.
  3. The Pod is assigned to a node. That node's kubelet reads the listed Secrets from the API server.
  4. The kubelet picks the login whose registry host matches the image name and sends it, with the pull request, to the container runtime over the CRI.
  5. The runtime authenticates to the registry and downloads the layers.

Three consequences follow from this path:

  • The Secret must be in the same namespace as the Pod. A Pod cannot refer to a Secret in another namespace. One registry login used by three namespaces means three Secrets.
  • A missing Secret does not block the Pod. The API server does not check that the name exists. The kubelet logs a FailedToRetrieveImagePullSecret warning and tries the pull without a login, which then fails for a private image. A typo in the Secret name therefore looks just like a wrong password, except for that one event.
  • The container never sees the login. Pull secrets are not mounted into the Pod and are not environment variables. They are used by the node and nowhere else.

imagePullSecrets is a list, so one Pod can pull from several private registries. It covers every container in the Pod, including init containers.

Letting the ServiceAccount carry the secret

A ServiceAccount adds the pull secret for youcreatelooked upaddsunchangedPod webno imagePullSecretsAPI serverServiceAccount admissionPod webregcred addedServiceAccountimagePullSecrets: regcredPod batchlists other-credPod batchkeeps other-cred only
A ServiceAccount adds the pull secret for you. When a Pod is created without imagePullSecrets, the API server copies the list from its ServiceAccount. A Pod that brings its own list is left alone.

Parts:

  • Pod web (no imagePullSecrets)
  • API server (ServiceAccount admission)
  • Pod web (regcred added)
  • ServiceAccount (imagePullSecrets: regcred)
  • Pod batch (lists other-cred)
  • Pod batch (keeps other-cred only)

Connections:

  • Pod web to API server: create
  • ServiceAccount to API server: looked up
  • API server to Pod web: adds
  • Pod batch to Pod batch: unchanged

Every Pod runs as a ServiceAccount (default if you name none). A ServiceAccount has its own imagePullSecrets list. When a Pod is created without imagePullSecrets, the ServiceAccount admission controller in the API server copies the ServiceAccount's list into the Pod. You can see the result in the stored Pod:

kubectl get pod web -o jsonpath='{.spec.imagePullSecrets}'
# [{"name":"regcred"}]

Two details matter:

  • The copy happens once, when the Pod is created. Pods that already exist are not changed, so a Pod stuck in ImagePullBackOff must be deleted and recreated after you fix the ServiceAccount.
  • A Pod that lists its own imagePullSecrets gets nothing added. The two lists are not merged.

When the image is pulled: imagePullPolicy

Each container has an imagePullPolicy:

PolicyWhat the kubelet does at container start
AlwaysAsks the runtime to contact the registry every time. Layers already on the node are not downloaded again, but the registry must be reachable and the login must be valid
IfNotPresentPulls only if the node has no copy of that image
NeverNever pulls. Uses a copy that is already on the node, or fails with ErrImageNeverPull

If you leave the field out, the API server fills it in when the object is created:

Image written asDefault policy
nginx (no tag) or nginx:latestAlways
nginx:1.29 (any other tag)IfNotPresent
nginx@sha256:… (digest)IfNotPresent

The default is set once. If you later edit a Deployment from nginx:latest to nginx:1.29, the policy that was written at creation (Always) stays.

Under the hood · Other ways a node can get registry credentials

An image pull secret is the method to know for the exam, but it is not the only one.

  • Runtime configuration on the node. An administrator can put a registry login in the containerd configuration. Every Pod on that node can then pull from the registry, and no Pod needs imagePullSecrets. This is simple, but it is all or nothing.
  • Kubelet credential provider plugins. Managed clusters use these. The kubelet runs a small program that fetches a short-lived token for the cloud's own registry using the node's identity. This is why Pods on a managed cluster can usually pull from that cloud's registry with no Secret at all.
  • Pre-pulled images. The image is put on the node in advance and the Pod uses imagePullPolicy: Never or IfNotPresent. Useful for air-gapped clusters.

All of them end in the same place: the container runtime holds a credential when it talks to the registry.

Under the hood · Allowing only trusted registries

Pull secrets control whether the cluster can fetch an image. They do not stop someone from running image: some-stranger/miner from a public registry. Restricting which images may run is a job for admission control, which you met in the Scheduling section. A ValidatingAdmissionPolicy can reject Pods whose images do not come from your registry with an expression such as:

object.spec.containers.all(c, c.image.startsWith('registry.example.com/'))

Checking image signatures and scanning images for known vulnerabilities go further in the same direction. They are CKS topics, not CKA ones.

Using it

Example · Pull a private image with a Pod-level secret

Create the Secret in the namespace where the Pod will run:

kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=deploy \
  --docker-password='S3cret!' \
  -n shop

--docker-email exists but is optional. For Docker Hub the server is https://index.docker.io/v1/.

Generate the Pod and add the last two lines:

kubectl run api -n shop --image=registry.example.com/shop/api:2.4 --dry-run=client -o yaml > api.yaml
apiVersion: v1
kind: Pod
metadata:
  name: api
  namespace: shop
spec:
  containers:
    - name: api
      image: registry.example.com/shop/api:2.4
  imagePullSecrets:             # same level as containers
    - name: regcred
kubectl apply -f api.yaml
kubectl get pod api -n shop
kubectl describe pod api -n shop | grep -A6 Events

A successful pull shows Pulling followed by Pulled, Created and Started.

Example · Fix a Deployment stuck in ImagePullBackOff

The Deployment api in namespace shop shows 0/3 ready. Start with the events of one Pod:

kubectl get pods -n shop
kubectl describe pod -n shop -l app=api | grep -E "Failed|Secret"

The message says pull access denied ... may require authorization, and the image name is spelled correctly, so the login is missing. Check what the Pod template lists and what exists:

kubectl get deploy api -n shop -o jsonpath='{.spec.template.spec.imagePullSecrets}'   # empty
kubectl get secrets -n shop                                                           # regcred exists

Add the list to the Pod template. kubectl edit works, and so does one patch:

kubectl patch deployment api -n shop \
  -p '{"spec":{"template":{"spec":{"imagePullSecrets":[{"name":"regcred"}]}}}}'
kubectl rollout status deployment api -n shop

Changing the Pod template starts a rollout, so the new Pods are created with the secret and the broken ones are removed. A bare Pod is different: imagePullSecrets cannot be changed on a live Pod, so you would recreate it with kubectl replace --force -f.

Example · Give every Pod in a namespace the pull secret

Attach the Secret to the namespace's default ServiceAccount:

kubectl patch serviceaccount default -n shop \
  -p '{"imagePullSecrets":[{"name":"regcred"}]}'
kubectl get serviceaccount default -n shop -o yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: default
  namespace: shop
imagePullSecrets:               # top level, not under spec
  - name: regcred

Now a Pod with no imagePullSecrets of its own gets them at creation:

kubectl run web -n shop --image=registry.example.com/shop/web:1.0
kubectl get pod web -n shop -o jsonpath='{.spec.imagePullSecrets}'    # [{"name":"regcred"}]

If a workload runs as another ServiceAccount (spec.serviceAccountName), patch that one instead.

Example · Check what is inside a pull secret

When the secret exists and the pull is still refused, look inside it:

kubectl get secret regcred -n shop -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d
{"auths":{"registry.example.org":{"username":"deploy","password":"S3cret!","auth":"ZGVwbG95OlMzY3JldCE="}}}

Here the server is registry.example.org but the image is on registry.example.com. The hosts do not match, so the kubelet never uses this login. A Secret's type cannot be changed and editing base64 by hand is slow, so delete and recreate it:

kubectl delete secret regcred -n shop
kubectl create secret docker-registry regcred -n shop \
  --docker-server=registry.example.com --docker-username=deploy --docker-password='S3cret!'
kubectl delete pod api -n shop        # or wait for the next back-off retry

The kubelet reads the Secret again on the next pull attempt, so a Pod in back-off recovers on its own within a few minutes. Deleting it is only quicker.

Example · Pin an image by digest

Find the digest of the image a running Pod actually uses, then use it in the manifest:

kubectl get pod api -n shop -o jsonpath='{.status.containerStatuses[0].imageID}'
# registry.example.com/shop/api@sha256:9b7c1d0e...
containers:
  - name: api
    image: registry.example.com/shop/api@sha256:9b7c1d0e...

Every node now runs byte-for-byte the same image, whatever happens to the tag 2.4 in the registry.

Tricks

Common mistakes

  • Creating the Secret in the wrong namespace. It must be in the namespace of the Pod. Forgetting -n puts it in default.
  • Putting imagePullSecrets inside a container. It belongs to the Pod: spec.imagePullSecrets, at the same level as containers. In a Deployment that is spec.template.spec.imagePullSecrets, not spec.imagePullSecrets.
  • Writing a string instead of a list of names. The value is - name: regcred, not imagePullSecrets: regcred.
  • Using kubectl create secret generic. That makes an Opaque Secret, which the kubelet does not accept as a registry login. Use docker-registry, or generic with --type=kubernetes.io/dockerconfigjson and the key .dockerconfigjson.
  • A server that does not match the image. The --docker-server host must be the host in the image name.
  • Expecting a ServiceAccount change to repair existing Pods. The secret is added only when a Pod is created.
  • Trusting latest. It is a moving tag, and with the default Always policy each node may fetch a different image on the next restart. Use a version tag or a digest.

Recap

  • An image name is registry/repository:tag or registry/repository@digest. Missing parts default to docker.io, library/ and :latest.
  • The node pulls the image. For a private registry, the kubelet takes the login from an image pull secret and gives it to the container runtime.
  • Create the secret with kubectl create secret docker-registry NAME --docker-server=… --docker-username=… --docker-password=…, in the Pod's namespace. Its type is kubernetes.io/dockerconfigjson.
  • Use it with spec.imagePullSecrets in the Pod (or Pod template), or attach it to the ServiceAccount so new Pods get it automatically.
  • imagePullPolicy defaults to Always for :latest or no tag and to IfNotPresent otherwise.
  • ErrImagePull and ImagePullBackOff only say that the pull failed. The Failed event in kubectl describe pod says why.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • A Deployment is stuck because its image lives in a registry that wants a login. Give the Pods the login as a pull secret and get the app running.

    Fix · Level 2 · standard · target 15 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.