# Containers in CI

Course: [CI/CD](https://www.devtutorials.ai/learn/cicd) · Section: Continuous Integration
Source: https://www.devtutorials.ai/learn/cicd/continuous-integration/containers-in-ci

> Write a small multi-stage Dockerfile, build and push the image from the pipeline, tag it with the commit, cache layers, scan it with Trivy, and record where it came from.

## Containers in CI

In the last lesson the artifact was a folder. Most teams now ship a **container image** instead.

- An image holds the app **and** everything it needs to run.
- The same image runs on your laptop, in staging and in production.
- It is still an artifact: build it once, tag it with a version, promote the same image.

You will:

- write a small, safe Dockerfile.
- build and push the image from the pipeline.
- tag it with the commit, cache it, scan it, and record where it came from.

**Simple lesson:** an image is an artifact that brings its own machine.

### A Real-World Example

Think about a tiffin box packed at home.

- The food, the spoon and the napkin go in one sealed box.
- It tastes the same in school, on the bus or at a friend's house.
- You do not pack the stove and the pressure cooker. Only the food.
- The box has your name on it, so nobody takes the wrong one.

Now map it:

- **Sealed tiffin** = container image.
- **Not packing the stove** = multi-stage build: leave build tools out.
- **Name on the box** = image tag, like the commit SHA.

**Simple lesson:** pack only what the app needs to run, and label it.

**Real tools vs this lab:** the Docker lab does not run Docker. It reads your Dockerfile and works out the size, the cached layers and the warnings, using real numbers from these base images. Try the starter repo's Dockerfile on your own laptop to see the real thing.

## The Dockerfile

A **Dockerfile** is a recipe for the image. Each line makes a **layer**.

- `FROM` picks a starting image.
- `WORKDIR` picks the folder.
- `COPY` copies files in. `RUN` runs a command.
- `CMD` or `ENTRYPOINT` says how the app starts.

A **multi-stage** Dockerfile has two `FROM` lines:

1. Stage 1 has all the build tools. It builds the app.
2. Stage 2 is a small runtime image. It copies **only** the built app from stage 1.

**Simple lesson:** build in a big stage, run in a small one.

## Fast Rebuilds: Layer Order

- Docker reuses a layer if nothing it depends on has changed. This is the **layer cache**.
- Once one layer changes, every layer after it is built again.
- Code changes often. Package lists change rarely.

So copy the package files first, install, **then** copy the code.

**Simple lesson:** put the things that change least at the top.

## Do Not Run as Root

- By default, many images run the app as **root**, the all-powerful user.
- If someone breaks into the app, they get full control of the container.
- React: serve with `nginxinc/nginx-unprivileged`. It listens on port 8080 as a normal user.
- .NET: add `USER $APP_UID`. Microsoft's images already have that user.

**Simple lesson:** give the app only the power it needs.

## Build and Push from the Pipeline

The pipeline builds the image and **pushes** it to a **registry**, a store for images.

This course uses **GitHub Container Registry** (`ghcr.io`).

| Platform | Sign in | Build and push |
|---|---|---|
| GitHub Actions | `docker/login-action` with `GITHUB_TOKEN` | `docker/build-push-action` |
| Azure Pipelines | a Docker Registry service connection | `Docker@2` with `buildAndPush` |

On GitHub, `GITHUB_TOKEN` can only push packages if the job has `packages: write`. That is the least-privilege rule from Pipeline Security, used for real.

**Simple lesson:** sign in to the registry, then build and push in one step.

## Tag with the Commit

- `latest` is a moving label. Every push overwrites it.
- With `latest` you cannot tell which code is running, or go back to an older image.
- Tag with the commit SHA: `ghcr.io/shop/shop-web:3f9c2ab...`

**Simple lesson:** one commit, one image tag, forever.

## Cache Image Layers in CI

Each run starts on a fresh runner with no Docker layers. So the layer cache is empty.

- `cache-from: type=gha` loads layers saved by earlier runs.
- `cache-to: type=gha,mode=max` saves them for the next run.
- Press **Run** twice. The second run is much faster.

**Simple lesson:** save Docker layers between runs, like you saved npm packages.

## Scan the Image

- Your image includes a base image with hundreds of system packages.
- Some have known security holes, called **CVEs**.
- **Trivy** is a free scanner. It lists them by how serious they are.
- Without `--exit-code 1`, Trivy only prints. The run stays green.

The fix for a base-image CVE is usually a newer base image tag. Do not just turn the scan off.

**Simple lesson:** a scan that cannot fail the run is only a report.

## Record Where the Image Came From

An **attestation** is a signed note that says: "this image was built from this commit, by this workflow."

- Anyone can check it later with `gh attestation verify`.
- It proves nobody swapped the image after the build.
- The note is signed with the job's OIDC token, so it needs `id-token: write`.

**Simple lesson:** sign a receipt for every image you ship.

1. Your starter repo already has a Dockerfile. On your laptop run `docker build -t shop-web .` then `docker run -p 8080:8080 shop-web`.
2. Open `http://localhost:8080/health`.
3. Push to main. The build-image job pushes to `ghcr.io/<you>/shop-web`.
4. Open your GitHub profile → **Packages** → shop-web.

**What you should see:** an image tagged with your commit SHA, and an attestation under it.

## Quick Check

## Cheat Sheet

Dockerfile (React):

```dockerfile
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginxinc/nginx-unprivileged:1.27-alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 8080
```

Dockerfile (.NET):

```dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY Shop/*.csproj Shop/
RUN dotnet restore Shop
COPY . .
RUN dotnet publish Shop -c Release -o /app/out

FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app/out .
USER $APP_UID
EXPOSE 8080
ENTRYPOINT ["dotnet", "Shop.dll"]
```

GitHub Actions:

```yaml
  build-image:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      attestations: write
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: build
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: ghcr.io/shop/shop-web:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
      - name: Scan the image
        run: |
          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
          trivy image --exit-code 1 --severity CRITICAL,HIGH ghcr.io/shop/shop-web:${{ github.sha }}
      - uses: actions/attest-build-provenance@v2
        with:
          subject-name: ghcr.io/shop/shop-web
          subject-digest: ${{ steps.build.outputs.digest }}
          push-to-registry: true
```

Azure Pipelines:

```yaml
  - job: build_image
    dependsOn: test
    steps:
      - task: Docker@2
        inputs:
          containerRegistry: ghcr-shop
          repository: shop/shop-web
          command: buildAndPush
          tags: $(Build.SourceVersion)
      - script: |
          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
          trivy image --exit-code 1 --severity CRITICAL,HIGH ghcr.io/shop/shop-web:$(Build.SourceVersion)
```

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| One-stage image with the SDK | Bigger is fine | Copy only the built app into a small stage | 1 GB images, slow deploys |
| `COPY . .` before install | Order does not matter | Copy package files first | Every change reinstalls everything |
| Tagging only `latest` | It is the newest | Tag with the commit SHA | No way to roll back to an exact build |
| No `packages: write` | GITHUB_TOKEN can do anything | It gets only what you give it | "permission_denied: write_package" |
| A secret in `ENV` | The image is private | Anyone who can pull it can read it | A key leaks |
| Scan without `--exit-code 1` | A scan protects you | It only prints | Known holes reach production |

## What to Remember

- An image is an artifact that brings its own machine.
- Multi-stage: build big, run small. Package files before code.
- Run as a normal user, not root. Pin base image versions.
- Push to a registry with the right permission. Tag with the commit SHA.
- Cache layers, scan with a gate, and attest where the image came from.

## Exercises

Next: **Pipeline Security**
