Lesson 2 of 3 Amazon ECS, ECR and Fargate

Building, Tagging and Managing Container Images in Amazon ECR

This lesson explains how to build efficient container images, push them to Amazon ECR from a pipeline, and manage them with tags, immutability, lifecycle policies and scanning.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the practices that make Dockerfiles small, fast to build and secure.
  • Explain how CodeBuild authenticates to and pushes images to Amazon ECR.
  • Explain why deployments reference immutable tags or digests.
  • Interpret the rules of an ECR lifecycle policy.

Writing a good Dockerfile

A Dockerfile lists the instructions that build an image, and each instruction creates a layer. Docker reuses unchanged layers from its cache, so the order of instructions decides how fast rebuilds are: steps that change rarely, such as installing dependencies, come before steps that change often, such as copying source code.

A multi-stage build installs or compiles in a first stage and copies only the results into a small runtime stage, so compilers and build caches never reach production. The following example builds a Python service from an image in Amazon ECR Public, pinned to a version, and runs it as a non-root user.

FROM public.ecr.aws/docker/library/python:3.12-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --target /deps -r requirements.txt

FROM public.ecr.aws/docker/library/python:3.12-slim
WORKDIR /app
COPY --from=build /deps /deps
COPY src/ ./src/
ENV PYTHONPATH=/deps
RUN useradd --uid 10001 app
USER app
EXPOSE 8080
CMD ["python", "-m", "src.server"]

A .dockerignore file excludes .git, local credentials, test data and virtual environments from the build context, which keeps them out of the image and speeds up the build. Images for Graviton instances or ARM-based Fargate tasks are built for linux/arm64, for example with docker buildx build --platform linux/arm64; an image built for the wrong architecture fails to start with an exec format error.

Pushing images from a pipeline

Amazon ECR authenticates Docker with a temporary token from aws ecr get-login-password. In AWS CodeBuild, the project needs privileged mode to run the Docker daemon and a service role with ECR push permissions, such as ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload and ecr:PutImage. The following buildspec.yml tags each image with the commit ID and writes the imagedefinitions.json file that CodePipeline's ECS deploy action reads.

version: 0.2
phases:
  pre_build:
    commands:
      - aws ecr get-login-password | docker login --username AWS --password-stdin $REGISTRY
      - TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c1-7)
  build:
    commands:
      - docker build -t $REGISTRY/orders-api:$TAG .
  post_build:
    commands:
      - docker push $REGISTRY/orders-api:$TAG
      - printf '[{"name":"orders-api","imageUri":"%s"}]' $REGISTRY/orders-api:$TAG > imagedefinitions.json
artifacts:
  files:
    - imagedefinitions.json

Tags, digests and immutability

A tag is a human-readable name for an image, such as 1.8.2 or 3f9c2ab, and a digest such as sha256:4b1c... is the hash of the image itself. By default a tag can be moved to a new image by pushing again with the same tag, so latest or even 1.8.2 may not mean the same image tomorrow. That makes rollbacks and audits unreliable.

Tag immutability on a repository rejects any push that would overwrite an existing tag. Exclusion filters, such as latest or dev-*, keep selected tags mutable while all others are immutable. Task definitions and manifests reference an immutable tag, such as the commit ID, or a digest, so each deployment can be traced to its source and redeployed exactly. ECR managed signing can also sign images on push, so deployment tools can verify that an image came from a trusted pipeline.

Lifecycle policies and scanning

Repositories grow with every build, and storage is charged. A lifecycle policy expires images automatically. Each rule has a priority, selects images by tag status and tag prefix, and counts them by number (imageCountMoreThan) or age (sinceImagePushed). The following policy expires untagged images after 14 days and keeps only the 30 most recent release images.

{
  "rules": [
    {"rulePriority": 1, "description": "Expire untagged images after 14 days",
     "selection": {"tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14},
     "action": {"type": "expire"}},
    {"rulePriority": 2, "description": "Keep the 30 most recent release images",
     "selection": {"tagStatus": "tagged", "tagPrefixList": ["release-"], "countType": "imageCountMoreThan", "countNumber": 30},
     "action": {"type": "expire"}}
  ]
}

A lifecycle policy preview lists the images a policy would expire before it is applied, which protects images that running services still use. Image scanning finds known vulnerabilities: basic scanning checks operating system packages on push or on demand, and enhanced scanning also checks programming language packages and rescans continuously as new vulnerabilities are published. Other repository features support larger teams: repository policies allow other accounts to pull, replication copies images to other Regions or accounts, and pull through cache rules keep copies of images from public registries such as Docker Hub in your account.

Scenario questions

Manage the images

Exam skills 3.1.2

Practise building and managing container images in ECR.

Log in to try this activity Interactive activities are free with an account.
Worked example

Cleaning up a busy repository

A team's ECR repository holds 4,000 images and its storage cost keeps rising. A rollback last week deployed the wrong code because someone had pushed a new image with the existing tag v2.3.

The developer enables tag immutability with an exclusion for dev-*, so release tags can never be overwritten while developers can still reuse their own scratch tags.

The pipeline now tags every image with the commit ID and a release- tag for production builds. A lifecycle policy, checked first with a preview, expires untagged images after 14 days and keeps the 30 most recent release images, which is more than the team's rollback window. Enhanced scanning reports vulnerable packages in each new image before it is deployed.

Check yourself

Why should a task definition reference an image by commit ID or digest rather than latest?

Show answer

latest can be moved to a different image by a later push, so the same task definition could run different code over time and a rollback would not restore the previous version.

Exam Tips

Remember for the exam

  • Smaller, safer images: a multi-stage Dockerfile that runs as a non-root user.
  • A tag must always mean the same image: tag immutability, with exclusions for scratch tags.
  • Expire untagged or old images automatically: an ECR lifecycle policy, checked with a preview.
  • CodeBuild needs privileged mode to build Docker images and ECR permissions to push them.
  • exec format error at container start: the image was built for the wrong CPU architecture.