Subscribe

Build once, deploy many: promoting one image through dev, staging and prod

Build the shorty image once per commit, tag it with the git SHA, and move the same digest through dev, staging and prod with config coming from the environment at runtime. With a local test that shows why rebuilding per environment gives you a different image.

Build once, deploy many: promoting one image through dev, staging and prod

A lot of pipelines build the app again for every environment. One job builds for dev, another builds the same commit for staging, and a third one builds it for prod. It feels harmless since the code is the same. But the thing you tested in staging is then not the thing you run in prod, it's only a close cousin of it.

In this blog we will look at the other way: build the image once per commit, give it an immutable tag (the git SHA), and promote that exact image through dev, staging and prod. The config that differs per environment comes in at runtime. This is an intermediate post in the CI/CD series after CI/CD explained: from git push to production, and it uses shorty, the URL shortener from the earlier tutorials. You should know what a Docker image and a tag are, and have read the GitHub Actions basics or at least seen a workflow file.

I used Go 1.27.3, crane and the in-memory registry from go-containerregistry v0.22.1, the distroless static-debian13 base, and actionlint 1.7.12 for the workflow.

Why rebuilding is risky

I wanted to see this with real numbers before repeating what everyone says. So I built shorty's image twice from the same commit, a few seconds apart, without changing a single file.

I didn't use Docker for this. Docker on my Mac is shared with quite a few other experiments, so I built the image with crane: compile a static binary, put it in a tar layer, and append that layer on top of the distroless base. It is the same thing the hardened distroless Dockerfile produces, just by hand.

go install github.com/google/go-containerregistry/cmd/crane@v0.22.1
go install github.com/google/go-containerregistry/cmd/registry@v0.22.1
registry -port 5323    # throwaway in-memory registry, leave it running in another terminal
SHA=$(git rev-parse HEAD)
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath \
  -ldflags "-s -w -X main.version=$SHA" -o img/root/shorty ./cmd/shorty
shasum -a 256 img/root/shorty
tar -C img/root -cf img/layer.tar shorty
crane append --platform linux/arm64 --base gcr.io/distroless/static-debian13:nonroot \
  -f img/layer.tar -t localhost:5323/shorty:tmp
crane mutate localhost:5323/shorty:tmp --cmd /shorty,serve --user 65532:65532 \
  --exposed-ports 8080 -t localhost:5323/shorty:$SHA

I ran it twice, second time with the tag rebuild. Here is what came back:

7b76bca119f734722fff6160000fd1c1ecf2e0b929f42299d0b03001484c3d49  img/root/shorty   (first build)
7b76bca119f734722fff6160000fd1c1ecf2e0b929f42299d0b03001484c3d49  img/root/shorty   (second build)
sha256:9cb39966a9fcf31e23668a17d27743e49bd01777b2bf6a65287a6a2051a9a745              shorty:<sha>
sha256:30b1fe81933e81af29e6629874f210c44fd9d70bc1a185aeade1b103ede6f06e              shorty:rebuild

The Go binary was byte for byte the same, Go is good at that with -trimpath. The image wasn't. The tar layer stores the file's modification time, so the layer digest changed, and with it the image digest. That was a tiny, boring difference and it still gave me two different images.

In a real pipeline the drift is bigger than a timestamp. Between the staging build and the prod build:

  • the base image tag can move (nonroot today points to one digest, next week to another),
  • a go mod download or apt-get install in the Dockerfile may fetch something newer,
  • a build arg can differ per environment,
  • the builder itself can get updated.

So basically the image in prod was never tested. You can chase reproducible builds (BuildKit supports SOURCE_DATE_EPOCH for the timestamp part), and it's a worthy hobby. But it's much simpler to never build twice.

One image, tagged with the git SHA

The rule is short. Build on merge to main, tag the image with the full commit SHA, push it once. After that nobody builds that commit again.

Why the SHA and not latest or staging? A SHA tag answers "what code is this?" without looking anything up. git show 8adcc28 and you know. And it never needs to move, because there's only ever one image for one commit. Tags like latest are pointers that move by design, which is exactly what you don't want when you're trying to work out what is running.

A tag can still be overwritten in most registries though. In ECR you can switch that off:

resource "aws_ecr_repository" "shorty" {
  name                 = "shorty"
  image_tag_mutability = "IMMUTABLE" # pushing an existing tag again fails

  image_scanning_configuration {
    scan_on_push = true
  }
}

I ran terraform validate on that with Terraform 1.17.1 and the AWS provider 6.73.0. With IMMUTABLE a second push of the same SHA tag fails instead of quietly replacing the image, and that's the behaviour you want.

Then go one step further and deploy by digest, not by tag. The digest (sha256:...) is the content hash of the image manifest. It can't be moved to point at something else. The tag is for humans, the digest is for the deploy.

Promoting without rebuilding

Promotion just means "this exact digest is now allowed in the next environment". There are two common ways to do it, and I tried both on the local registry:

crane tag localhost:5323/shorty:$SHA staging                         # add a tag in the same repo
crane digest localhost:5323/shorty:staging
crane copy localhost:5323/shorty:$SHA localhost:5323/prod/shorty:$SHA # copy to another repo
crane digest localhost:5323/prod/shorty:$SHA
sha256:9cb39966a9fcf31e23668a17d27743e49bd01777b2bf6a65287a6a2051a9a745
sha256:9cb39966a9fcf31e23668a17d27743e49bd01777b2bf6a65287a6a2051a9a745

Same digest both times. Adding a tag or copying between repositories never changes the bytes, so the digest stays. The copy is useful when prod lives in a different AWS account with its own ECR, which is a setup I like because the prod account then never needs pull access to the dev registry.

A small aside: the in-memory registry prints "Congratulations! You've won a lifetime's supply of free image pulls from this in-memory registry!" on every copy. It made me smile anyway. Somebody had fun writing that.

The pipeline

Here is the shape I use for shorty on GitHub Actions. One build job, then dev, staging and prod in a row, each one calling the same reusable deploy workflow with the same image reference:

name: pipeline

on:
  push:
    branches: [main]

permissions:
  contents: read
  packages: write

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      image: ${{ steps.ref.outputs.image }}
    steps:
      - uses: actions/checkout@v7
      - uses: docker/setup-buildx-action@v4
      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: push
        uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
          build-args: VERSION=${{ github.sha }}
      - id: ref
        run: echo "image=ghcr.io/${{ github.repository }}@${{ steps.push.outputs.digest }}" >> "$GITHUB_OUTPUT"

  dev:
    needs: build
    uses: ./.github/workflows/deploy.yml
    with:
      environment: dev
      image: ${{ needs.build.outputs.image }}
    secrets: inherit

  staging:
    needs: [build, dev]
    uses: ./.github/workflows/deploy.yml
    with:
      environment: staging
      image: ${{ needs.build.outputs.image }}
    secrets: inherit

  prod:
    needs: [build, staging]
    uses: ./.github/workflows/deploy.yml
    with:
      environment: prod
      image: ${{ needs.build.outputs.image }}
    secrets: inherit

The build job is the only place with a docker/build-push-action. Its digest output becomes ghcr.io/<repo>@sha256:... and that string is passed down unchanged. Note the VERSION build arg is the SHA too, so shorty version prints the commit everywhere.

The deploy workflow refuses anything that is not pinned by digest, then rolls it out. I used Kubernetes here because the kind tutorial already runs shorty as a Deployment called shorty, but the same job works with an ECS deploy step instead of kubectl.

name: deploy

on:
  workflow_call:
    inputs:
      environment:
        type: string
        required: true
      image:
        description: image by digest, e.g. ghcr.io/fenixara/shorty@sha256:...
        type: string
        required: true

permissions:
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment }}
    concurrency:
      group: deploy-${{ inputs.environment }}
      cancel-in-progress: false
    steps:
      - name: refuse anything that is not pinned by digest
        env:
          IMAGE: ${{ inputs.image }}
        run: |
          case "$IMAGE" in
            *@sha256:*) echo "deploying $IMAGE" ;;
            *) echo "image must be pinned by digest: $IMAGE"; exit 1 ;;
          esac
      - name: kubeconfig
        env:
          KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }}
        run: |
          mkdir -p ~/.kube
          printf '%s' "$KUBECONFIG_DATA" > ~/.kube/config
          chmod 600 ~/.kube/config
      - name: roll out
        env:
          IMAGE: ${{ inputs.image }}
        run: |
          kubectl -n shorty set image deployment/shorty shorty="$IMAGE"
          kubectl -n shorty rollout status deployment/shorty --timeout=5m

Each environment in GitHub has its own KUBECONFIG secret, so the same job talks to a different cluster depending on environment. Put required reviewers on the prod environment and the prod job waits for a click. The concurrency group stops two deploys to the same environment from overlapping. actionlint was clean on both files.

Config belongs to the environment

Build once only works if nothing environment specific is baked into the image. No ENV BASE_URL=... in the Dockerfile, no .env.prod copied in, no build arg that says "prod".

shorty was written for this from the start, every setting is an env var read at startup (the standard library API post has the list). So dev and prod differ only in what the platform passes in:

# dev.env
BASE_URL=https://dev.sho.example.com
LOG_LEVEL=debug
DB_MAX_CONNS=5
CACHE_TTL=1h
# prod.env
BASE_URL=https://sho.example.com
LOG_LEVEL=info
DB_MAX_CONNS=20
CACHE_TTL=24h

On Kubernetes these become a ConfigMap and a Secret per namespace, see the ConfigMaps and probes post. On ECS they go in the task definition. With Terraform the values usually live per environment directory, like in the workspaces vs directories post. Secrets like DATABASE_URL come from a secret store, never from the image.

One thing that actually trips people up is frontend builds. A single page app often bakes the API URL in at build time. If you have one, serve a small config.json from the backend at runtime instead, otherwise you are back to one build per environment.

Rolling back is a redeploy

The nice side effect: a rollback is the same deploy job with an older digest. No rebuild, no "let me revert and wait for CI". The deploy job prints the digest it rolled out (the deploying ... line above), so finding the previous one is a search through the old runs.

Two things still need care. The old image must still be in the registry, so don't let a lifecycle policy delete images that prod ran last week. And the database must still work with the old code, which is a migrations problem more than an images problem.

That's it. Build it once, pass the digest along, and let each environment bring its own config.