Push an Image to ECR

Build your image and push it to Amazon Elastic Container Registry.

Amazon ECR is a private Docker registry. Before ECS can run your app you build the image and push it to an ECR repository.

Build image, push to ECR, then deploy to ECSdockerbuildECRimage repoTask Definitionnew revisionECS Servicerolling update
A typical deploy: build the image, push to ECR, register a new task-definition revision, and update the service.

The three steps

  1. Authenticate Docker to ECR.
  2. Tag the image with the repository URI.
  3. Push it.

Example

Example · bash
# 1. Log in
aws ecr get-login-password --region us-east-1 \
  | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com

# 2. Tag  3. Push
docker tag my-app:1.0 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0

When to use it

  • A CI pipeline builds a Docker image on every merge to main and pushes it to ECR, giving ECS a new image to deploy without any manual steps.
  • A team tags images with both the git SHA and the word 'latest' so ECS services can pin to an immutable tag while automation updates 'latest' for quick demos.
  • A security-conscious team enables ECR image scanning on push so vulnerabilities in a new image are flagged before a developer triggers an ECS deployment.

More examples

Build and Push Image to ECR

Authenticates to ECR, builds the image tagged with both the git SHA and 'latest', then pushes both tags so deployments are traceable and automation-friendly.

Example · bash
REGION=us-east-1
ACCOUNT=123456789012
REPO=$ACCOUNT.dkr.ecr.$REGION.amazonaws.com/my-api
SHA=$(git rev-parse --short HEAD)

aws ecr get-login-password --region $REGION \
  | docker login --username AWS --password-stdin $ACCOUNT.dkr.ecr.$REGION.amazonaws.com

docker build -t $REPO:$SHA -t $REPO:latest .
docker push $REPO:$SHA
docker push $REPO:latest

Create ECR Repository

Creates an ECR repository with immutable image tags and on-push scanning so tags cannot be overwritten and every image is scanned automatically.

Example · bash
aws ecr create-repository \
  --repository-name my-api \
  --image-scanning-configuration scanOnPush=true \
  --image-tag-mutability IMMUTABLE

Set ECR Lifecycle Policy

Sets a lifecycle policy that keeps only the 20 most recent images in the repository, automatically expiring older ones to control storage costs.

Example · bash
aws ecr put-lifecycle-policy \
  --repository-name my-api \
  --lifecycle-policy-text '{
  "rules":[{
    "rulePriority":1,
    "description":"Keep last 20 images",
    "selection":{"tagStatus":"any","countType":"imageCountMoreThan","countNumber":20},
    "action":{"type":"expire"}
  }]
}'

Discussion

  • Be the first to comment on this lesson.