# Images and registries for Kubernetes

The container knowledge Kubernetes assumes: building a small, non-root image, tagging it properly, and pushing it to a registry the cluster can pull from, with a real push to Amazon ECR.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 2. About 20 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/02-containers-refresher

## What you will learn

- Build a small image that runs as a non-root user and listens on a known port
- Tag images with real versions instead of latest, and explain why Kubernetes cares
- Create a private registry in Amazon ECR and push images to it
- Explain how cluster nodes get permission to pull from a private registry

> **Lab status.** **Verified lab:** the shop-web image built with Docker and pushed to a real Amazon ECR repository in ap-south-1. The output shown is real. <br />**Code walkthrough:** none. <br />**Cloud lab:** ECR needs an AWS account (storage is a few cents per GB-month).

Kubernetes runs containers; it doesn't build them. Before a cluster can run your app, the app has to
be an image in a registry the nodes can reach. The Docker course covers images in depth. This lesson
is the short version Kubernetes needs, and it builds the **shop-web** app that every later lesson
deploys.

## An image built for Kubernetes

shop-web is a tiny Python web server. It answers `/` with a page, `/api` with JSON saying which
version and which Pod answered, `/healthz` for health checks, and `/burn` to use CPU in the
autoscaling lesson. The Dockerfile:

```dockerfile
FROM python:3.13-alpine
WORKDIR /app
COPY app.py .
RUN adduser -D -u 10001 app
USER 10001
EXPOSE 8080
ARG APP_VERSION=v1
ENV APP_VERSION=$APP_VERSION
CMD ["python", "app.py"]
```

Four choices here matter later:

1. **A small base image** (`python:3.13-alpine`). Smaller images pull faster when a Pod lands on a new
   node, which matters when autoscaling adds nodes under load.
2. **A non-root user** (`USER 10001`). The Security lesson enforces the restricted Pod Security
   standard; images that need root fail it.
3. **A fixed port** (`EXPOSE 8080`). The Service and health checks in later lessons point at 8080.
4. **The version comes from the build** (`ARG APP_VERSION`), so `/api` reports which version a Pod runs.
   That makes rollouts and rollbacks visible.

The lab built three images: **v1**, **v2**, and **v3-broken**, which exits on start with
`config error: DATABASE_URL is not set`. You'll use v3-broken to see a failed rollout, a
CrashLoopBackOff and a Helm rollback.

### Tags, not latest

Every Kubernetes manifest in this course names an exact tag: `shop-web:v1`. With `:latest`, two nodes
that pulled at different times can run different code under the same name, and "roll back to the
previous version" has no meaning. Tag every build with a version or the Git commit SHA, and never
reuse a tag.

> **Figure.** Two panels. Left, image shop-web:latest: at 09:00 node A pulls latest and gets the build that was current; at 11:00 a new build is pushed as latest; at 15:00 node B pulls latest and gets the new build. Result: two Pods, one tag, two versions; rolling back to the previous latest has no meaning, and latest defaults to imagePullPolicy Always. Right, image shop-web:v2: both nodes pull v2 and get exactly the same image; the next build is pushed as a new tag, v3, so v2 never changes; rollback is kubectl set image deployment/shop-web back to v1.
>
> Same tag name, different code: what latest does to two nodes that pull a few hours apart.

## Push it to a registry

A **registry** stores images; nodes pull from it. Docker Hub is public by default. For your own apps,
use a private registry next to your cluster: **Amazon ECR** on AWS.

> **Figure.** Flow from build to running Pod. Your laptop or CI builds and pushes shop-web:v2 (step 1) to Amazon ECR in ap-south-1, repository shop-web with tags v1, v2 and v3-broken, scan on push on, about 17 MB compressed, at 626159997645.dkr.ecr.ap-south-1.amazonaws.com. Step 2: kubectl apply sends a Pod spec naming the image URI and tag, and the scheduler picks a node. Step 3: the kubelet on the worker node pulls the image from ECR (v1 is already cached). Step 4: containerd starts the container in Pod shop-web. Bottom: the node may pull from ECR in the same account because its IAM role has AmazonEC2ContainerRegistryReadOnly; other private registries need a kubernetes.io/dockerconfigjson Secret listed as imagePullSecrets; a failed pull shows ErrImagePull, then ImagePullBackOff.
>
> Push once, pull on every node that runs the Pod. The node's IAM role is what lets it pull from ECR.

The lab created one:

```text
$ aws ecr create-repository --repository-name shop-web --image-scanning-configuration scanOnPush=true
{
    "name": "shop-web",
    "uri": "626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web",
    "scanOnPush": true
}
```

`scanOnPush` makes ECR scan every pushed image for known vulnerabilities. The URI has three parts: the
account ID, the region, and the repository name. That full URI, plus a tag, is what goes in your Pod
specs.

Log Docker in to ECR (the password is a short-lived token), tag, and push:

```text
$ aws ecr get-login-password --region ap-south-1 | docker login --username AWS --password-stdin 626159997645.dkr.ecr.ap-south-1.amazonaws.com
Login Succeeded
$ docker push 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1
$ docker push 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v2
$ docker push 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v3-broken
$ aws ecr describe-images --repository-name shop-web
---------------------------------------------------------------
|                       DescribeImages                        |
+-----------------------------------+-----------+-------------+
|              pushed               |  sizeMB   |     tag     |
+-----------------------------------+-----------+-------------+
|  2026-11-09T05:40:15.891000+00:00 |  16943891 |  None       |
|  2026-11-09T05:40:15.900000+00:00 |  1166     |  None       |
...
|  2026-11-09T05:40:20.282000+00:00 |  16944155 |  v3-broken  |
|  2026-11-09T05:40:18.329000+00:00 |  16943891 |  v2         |
|  2026-11-09T05:40:16.233000+00:00 |  16943891 |  v1         |
+-----------------------------------+-----------+-------------+
```

(The `sizeMB` column is really bytes: about 17 MB compressed, against 70 MB locally.) The untagged
entries surprise people: Docker's build tooling attaches **attestations** (provenance records of how
the image was built) and a multi-platform index, which the registry stores as separate manifests.
They're expected, not junk.

### How nodes get permission to pull

ECR repositories are private. On EKS, the worker node group's IAM role carries the
`AmazonEC2ContainerRegistryReadOnly` policy, so the kubelet on each node can pull from ECR in the same
account with no password stored anywhere. For other private registries (GitHub Container Registry, a
Docker Hub private repo), you create a Secret of type `kubernetes.io/dockerconfigjson` and reference it
in the Pod spec as `imagePullSecrets`.

When a pull fails, the Pod shows **ErrImagePull**, then **ImagePullBackOff**. The Monitoring lesson
reproduces it with a tag that doesn't exist.

## Mission: Publish an image your cluster can pull

Build shop-web as v1 and v2 (different APP_VERSION build args), create a private repository with scan on push, push both tags, and list them. Record the repository URI and both image digests.

- You need: The Dockerfile and app from this lesson
- You'll have: ~/registry.txt

```sh
$ docker build -t shop-web:v1 --build-arg APP_VERSION=v1 .
$ docker build -t shop-web:v2 --build-arg APP_VERSION=v2 .
$ aws ecr create-repository --repository-name shop-web --image-scanning-configuration scanOnPush=true
$ REG=<account>.dkr.ecr.<region>.amazonaws.com
$ aws ecr get-login-password | docker login --username AWS --password-stdin $REG
$ for t in v1 v2; do docker tag shop-web:$t $REG/shop-web:$t && docker push $REG/shop-web:$t; done
$ aws ecr describe-images --repository-name shop-web --query 'imageDetails[].[imageTags[0],imageDigest]' --output text > ~/registry.txt
```

You should see v1 and v2 with digests (and possibly untagged attestation entries). No AWS account? Push
to Docker Hub or GitHub Container Registry instead; the Kubernetes side is the same, with an
imagePullSecret.

## Try it

- Build the shop-web image from this lesson and run it locally with `docker run -p 8080:8080`.
- Call `/api` and `/healthz` with curl and read the JSON.
- Create an ECR repository with scan on push enabled.
- Push two tags, v1 and v2, and list them with `aws ecr describe-images`.
- Do the mini mission and keep `~/registry.txt`.

## Quiz

1. Why should Kubernetes manifests use image tags like v2 instead of latest?
   - latest is slower to download
   - **A fixed tag means every node runs exactly the same code, and a rollback can point back to a known version** (answer)
   - Kubernetes rejects latest
   Why: latest can mean different images on different nodes depending on when each pulled it, and you can't roll back to "the previous latest".

2. How do EKS worker nodes get permission to pull from a private ECR repository in the same account?
   - You paste a password into every manifest
   - **The node's IAM role includes ECR read permissions, so the kubelet can pull without stored credentials** (answer)
   - ECR repositories are always public
   Why: The node group's role has the AmazonEC2ContainerRegistryReadOnly policy. Other registries use imagePullSecrets instead.

3. The image runs as user 10001 instead of root. Why does that matter in Kubernetes?
   - It makes the image smaller
   - **It limits the damage if the app is compromised, and it is required by the restricted Pod Security standard** (answer)
   - Kubernetes can only run non-root images
   Why: The Security lesson shows a cluster rejecting a privileged Pod. Running as non-root from the start means your images pass those rules.

## Resources

- [Images (Kubernetes concepts)](https://kubernetes.io/docs/concepts/containers/images/) (Kubernetes)
- [Amazon ECR user guide](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) (AWS Docs)
- [Using Amazon ECR images with Amazon EKS](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ECR_on_EKS.html) (AWS Docs)
- [Pull an image from a private registry](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/) (Kubernetes)
