Skip to content

Lesson 17 of 24Security and supply chain

Registries and Image Distribution

How registries store and serve images, how to authenticate without long-lived passwords, promote by digest, dodge rate limits, and keep storage under control.

15 min read0/4 questions

Two incidents in one week. On Tuesday every CI job fails with toomanyrequests: You have reached your pull rate limit, because forty runners behind one NAT address all pulled python:3.13-slim from Docker Hub anonymously. On Thursday a bad release goes out, and the rollback "to the previous latest" redeploys the same broken image, because latest already pointed at it. Neither incident involved a bug in your code. Both came from treating the registry as a dumb file server. Images and Containers introduced registries as the place images travel through, and Containers on AWS showed the basic ECR push. This lesson covers how a registry works underneath and the operational habits that keep releases reproducible and builds unblocked.

One protocol, many registries

Every serious registry speaks the OCI Distribution Specification, an HTTP API under /v2/. That is why docker, podman, crane, skopeo, Kubernetes and your CI tools all work against any of them, and why you can move images from one to another without rebuilding.

RegistryWhere it fitsThings to know
Docker Hub (docker.io)Public images, official imagesPull rate limits, especially for anonymous pulls
GitHub Container Registry (ghcr.io)Code on GitHubAuth with GITHUB_TOKEN in Actions; permissions follow the repo
Amazon ECRWorkloads on AWSIAM auth, tag immutability, lifecycle policies, pull-through cache
Google Artifact RegistryWorkloads on GCPAlso hosts language packages (npm, Maven, Python)
Azure Container RegistryWorkloads on AzureGeo-replication on premium tiers
Harbor (self-hosted)On-prem, air-gapped, or regulatedOpen source CNCF project with scanning, replication and proxy caching

An image reference packs four parts: registry/repository:tag@digest. ghcr.io/acme/api:sha-7f3c2a1 names registry ghcr.io, repository acme/api, tag sha-7f3c2a1. When you write only python:3.13-slim, Docker expands it to docker.io/library/python:3.13-slim. That hidden default is why a bare image name in a Dockerfile is a dependency on Docker Hub, with its limits and outages, whether you meant it or not.

What a pull actually does

A registry stores two kinds of things. Blobs are layer tarballs and config files, each stored under the SHA-256 digest of its bytes. Manifests are small JSON documents that list a config blob and the layer blobs, also addressed by digest. A tag is just a name that points at one manifest digest, and anyone with push rights can move it.

docker pull ghcr.io/acme/api:sha-7f3c2a1
ClientRegistryToken serviceGET /v2/401 + where to get a tokencredentials, scope repository:acme/api:pullbearer tokenGET manifest for tag sha-7f3c2a1image index (amd64, arm64)GET blobs by digest (only missing ones)

The client checks the API and learns how to authenticate.

1/7

Two consequences follow. First, a digest is a promise and a tag is not. The same tag can resolve to different content tomorrow; the same digest cannot, because the digest is computed from the content. Second, identical content gets an identical digest, so registries store each layer once, no matter how many tags or repositories reference it.

This toy registry shows both. It stores manifests by the hash of their content and keeps tags as movable pointers.

Pythonregistry.py
import hashlibimport json manifests: dict[str, str] = {} # digest -> manifest JSON (content-addressed)tags: dict[str, str] = {} # tag -> digest (just a movable pointer) def push(tag: str, layers: list[str]) -> str: body = json.dumps({"schemaVersion": 2, "layers": layers}, sort_keys=True) digest = "sha256:" + hashlib.sha256(body.encode()).hexdigest() manifests[digest] = body tags[tag] = digest return digest def pull(ref: str) -> str: digest = ref if ref.startswith("sha256:") else tags[ref] return json.loads(manifests[digest])["layers"][-1] v1 = push("latest", ["python-base", "app-v1"])deployed_tag, deployed_digest = "latest", v1print("deployed:", pull(deployed_tag), v1[:19]) v2 = push("latest", ["python-base", "app-v2"]) # a bad release, same tagprint("v2 pushed:", v2[:19]) print("rollback by tag ->", pull(deployed_tag))print("rollback by digest->", pull(deployed_digest)) again = push("sha-7f3c2a1", ["python-base", "app-v1"]) # same content, new tagprint("same content, same digest:", again == v1)print("manifests stored:", len(manifests), "tags:", sorted(tags))
Output
Press Run (⌘ Enter) to see what happens.

That is Thursday's incident in miniature. The deploy system remembered a tag, and the tag had moved. Had it remembered the digest, rollback would have worked.

Authentication without long-lived passwords

docker login stores credentials for a registry in ~/.docker/config.json. By default on a laptop they go into the OS keychain through a credential helper (osxkeychain on macOS, wincred on Windows, desktop with Docker Desktop), not into the file in plain text. Check that file on a CI runner or a server: if it contains an auths entry with a base64 auth value, that is your password, merely encoded.

Cloud registries add helpers that fetch short-lived tokens on demand. For ECR, docker-credential-ecr-login uses your AWS credentials directly, so you never run docker login at all:

~/.docker/config.json
{
  "credHelpers": {
    "123456789012.dkr.ecr.us-east-1.amazonaws.com": "ecr-login"
  }
}

Without the helper, the manual form exchanges IAM credentials for a token that lasts 12 hours:

aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com

Google uses gcloud auth configure-docker and Azure uses az acr login --name <registry>; both set up helpers the same way.

In CI, use OIDC instead of stored secrets. GitHub Actions can push to GHCR with the built-in GITHUB_TOKEN (scoped with permissions: packages: write). For ECR, aws-actions/configure-aws-credentials exchanges the job's OIDC token for a role session that lasts about an hour, then the ECR login action uses it. Nothing long-lived sits in your repository secrets for a worm to steal.

In Kubernetes, the node's kubelet pulls images, not your pod. There are two ways to give it credentials:

  • imagePullSecrets: a Secret of type kubernetes.io/dockerconfigjson referenced from the pod or its service account. Works anywhere, but it is a static credential you must rotate, and it has to exist in every namespace that needs it.
  • Node identity: on EKS, the node IAM role gets a read-only ECR policy and the kubelet's credential provider fetches tokens automatically. GKE and AKS do the equivalent. No secret to copy around or rotate.

Prefer node identity for your own cloud registry and keep imagePullSecrets for third-party private registries.

Tags, digests and promotion

With the pull model in mind, the rules for deploy manifests write themselves:

  • Deploy by digest, or by a tag that can never move. image: ghcr.io/acme/api@sha256:4c1e... is exact. A sha-7f3c2a1 tag is nearly as good if your registry enforces it cannot be overwritten.
  • Turn on tag immutability. ECR repositories support IMMUTABLE tags: a push to an existing tag fails with ImageTagAlreadyExistsException. ECR also supports exclusion filters (IMMUTABLE_WITH_EXCLUSION) so a convenience tag like latest or main can still move while sha-* and version tags cannot.
  • Never deploy latest. Besides the rollback problem, Kubernetes treats :latest specially and defaults to imagePullPolicy: Always, so two nodes can run different code under the same pod spec.

Promote, do not rebuild. The image you tested in staging should be the exact bytes that run in production. Rebuilding for prod gives you a new digest with possibly different base layers, and your staging tests no longer apply. Promotion means copying or retagging the same digest:

crane copy 111111111111.dkr.ecr.us-east-1.amazonaws.com/api@sha256:4c1e9f0b... 222222222222.dkr.ecr.us-east-1.amazonaws.com/api:1.4.2skopeo copy --all docker://ghcr.io/acme/api@sha256:4c1e9f0b... docker://registry.example.com/acme/api:1.4.2docker buildx imagetools create -t ghcr.io/acme/api:prod ghcr.io/acme/api@sha256:4c1e9f0b...

crane (from Google's go-containerregistry) and skopeo (from the containers project) talk to registries directly, with no Docker daemon and no local pull and push. crane copy copies every platform and keeps the digest. With skopeo, pass --all or it copies only the image for your own machine's platform and you end up with a different digest. imagetools create is handy for adding a tag to an existing digest in the same registry. Copies within one registry are cheap because layers already exist; only the manifest is new.

Quick check
Staging tested ghcr.io/acme/api@sha256:4c1e.... The release job rebuilds from the same git commit and pushes 1.4.2 for production. What is the main risk?
Need a nudge? A hint rules out a wrong answer.

Rate limits, mirrors and pull-through caches

Docker Hub limits pulls per 6-hour window: about 100 for anonymous users per IPv4 address or IPv6 /64, and 200 for authenticated free accounts, with paid plans much higher (check the Docker docs, these numbers have changed several times). Every runner behind one NAT gateway shares the anonymous limit, which is exactly Tuesday's outage.

Fixes, from quickest to most durable:

  1. Log in to Docker Hub in CI, even with a free account, to move from the IP limit to an account limit.
  2. Mirror Docker Hub. The daemon's registry-mirrors setting in daemon.json sends Docker Hub pulls through a mirror you run. It only works for Docker Hub images; other registries cannot be mirrored this way.
  3. Use a pull-through cache. ECR pull-through cache rules fetch an upstream image on first pull, store it in your account, and serve later pulls locally, checking upstream for a newer version of the tag once the cached copy is more than 24 hours old. ECR supports Docker Hub (credentials stored in Secrets Manager under an ecr-pullthroughcache/ prefix), GHCR, Quay, the Kubernetes registry, ECR Public and others. Harbor offers proxy-cache projects for the same job on-prem.
docker pull 123456789012.dkr.ecr.us-east-1.amazonaws.com/docker-hub/library/python:3.13-slim

Official Docker Hub images need the library/ part in that path. Point your Dockerfiles' FROM lines at the cache and you also survive Docker Hub outages, because cached images keep being served when upstream is down. As a bonus, pulls stay inside your cloud network.

Retention and lifecycle

A busy repository pushes an image per commit. Each image shares most layers with the last, but the unique layers add up, and untagged manifests (left behind when a tag moves) pile up silently. Storage is billed per GB-month, so without cleanup the bill only grows.

ECR lifecycle policies are rules evaluated in priority order. A common pair: keep the last 50 sha- images, and expire untagged images after 7 days.

lifecycle-policy.json
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Expire untagged images after 7 days",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 7
      },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 2,
      "description": "Keep the newest 50 sha- images",
      "selection": {
        "tagStatus": "tagged",
        "tagPatternList": ["sha-*"],
        "countType": "imageCountMoreThan",
        "countNumber": 50
      },
      "action": { "type": "expire" }
    }
  ]
}

The danger is that a lifecycle policy knows nothing about what is running. An image deployed to production months ago, during a quiet period, can fall out of "the newest 50" and be deleted; the running containers keep going until a node restarts or scales out and the pull fails. Protect release images with a separate tag pattern the count rule does not match, and keep counts generous.

Predict the outputPython

What does this print?

images = [  # (tags, days since push)
  (["sha-a1"], 30), (["sha-b2"], 20), ([], 10),
  (["sha-c3", "prod"], 9), ([], 3), (["sha-d4"], 1),
]
sha = sorted((i for i in images if any(t.startswith("sha-") for t in i[0])), key=lambda i: i[1])
expired = sha[2:]  # keep the 2 newest sha- images
expired += [i for i in images if not i[0] and i[1] > 7]  # untagged, older than 7 days
print(len(expired), [tags for tags, days in expired])
Need a nudge? Hints walk you through it.

More than images: OCI artifacts

Because a registry is just content-addressed storage with a manifest format, it can hold other things. These are OCI artifacts:

  • Helm charts: helm push mychart-0.4.0.tgz oci://ghcr.io/acme/charts stores a chart next to the images it deploys, with the same auth and replication.
  • Signatures, SBOMs and attestations: Scanning, SBOMs and Signed Images attached these to images. OCI 1.1 added a subject field so an artifact can point at the image it describes, and a referrers API (GET /v2/<name>/referrers/<digest>) that lists everything attached to a digest. Copy tools that understand referrers carry signatures along when you promote; older ones leave them behind, which breaks admission checks in the target environment.
  • Anything else: the oras CLI pushes arbitrary files (ML model weights, policy bundles, WASM modules) as artifacts.

Golden base images

Larger companies rarely let every team pull python:3.13-slim from the internet. A platform team publishes golden images to an internal repository, such as registry.acme.internal/base/python:3.13, built from an upstream or hardened base plus company CA certificates, a standard non-root user, and agreed settings. They rebuild it weekly, scan and sign it, and teams FROM it. One base bump then patches every service on its next build, and security reviews one image instead of two hundred Dockerfiles. The cost is a dependency on the platform team's cadence, so golden images need a clear owner and a documented update schedule.

Match the pairs0/6 matched

Match each tool or feature to the job it does.

Choose an item, then its match on the other side.
Put it in order5 steps

Order a release that promotes one tested image from staging to production.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
OCI Distribution Spec
The standard HTTP API under /v2/ that every major registry implements for pushing and pulling.
manifest
A small JSON document listing an image's config and layer blobs by digest. Its own digest identifies the image.
image index
A manifest that points at one manifest per platform, so one tag can serve amd64 and arm64.
credential helper
A program Docker calls to fetch registry credentials from a keychain or cloud identity instead of storing them in a file.
pull-through cache
A registry that fetches upstream images on first pull, stores them, and serves later pulls itself.
tag immutability
A registry setting that rejects pushes which would move an existing tag to a new digest.
referrers API
The OCI 1.1 endpoint that lists artifacts, like signatures and SBOMs, attached to an image digest.