devHọc Dev

Week 1 - Day 3: ECR, Deploying to ECS Fargate, Security and Image Optimization

Week 1 – Day 3

This lesson combines 2 topics: Amazon ECR and Deploying to ECS Fargate, Security and Image Optimization.

Learning Objectives

  • Create an ECR repository and push a Docker image from your local machine
  • Understand the ECR authentication flow (aws ecr get-login-password)
  • Write an ECS Task Definition and create an ECS Service on Fargate
  • Understand the differences between the EC2 and Fargate ECS launch types
  • Get a high-level view of ECS vs EKS and when to use which
  • Reduce image size with multi-stage builds and slim base images
  • Scan for vulnerabilities with Trivy, ECR Scanning, and Inspector
  • Run containers as a non-root user
  • Manage secrets properly (never bake them into the image)
  • Understand SBOM (Software Bill of Materials) and why it matters
  • Put together a security checklist for production containers

Part 1: Amazon ECR and Deploying to ECS Fargate

1. Amazon ECR — Container Registry

Why do you need a private registry?

The Docker Hub public registry is convenient for open-source images but is not a good fit for production apps because:

  • Rate limiting on the free tier (100 pulls/6h for shared IPs)
  • Public images → anyone can pull them
  • No built-in integration with IAM policies

Amazon ECR solves all of these and integrates deeply with ECS/EKS/Fargate.

Create an ECR repository

# Create the repository
aws ecr create-repository \
  --repository-name myapp \
  --region ap-southeast-1 \
  --image-scanning-configuration scanOnPush=true \
  --encryption-configuration encryptionType=AES256

# Output:
# {
#   "repository": {
#     "repositoryArn": "arn:aws:ecr:ap-southeast-1:123456789012:repository/myapp",
#     "registryId": "123456789012",
#     "repositoryName": "myapp",
#     "repositoryUri": "123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/myapp",
#     ...
#   }
# }

Authentication — the most important part

# ECR uses a temporary token (12 hours), not a fixed username/password
# Get the token and pipe it into docker login

AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
AWS_REGION=ap-southeast-1

aws ecr get-login-password --region ${AWS_REGION} | \
  docker login \
    --username AWS \
    --password-stdin \
    ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com

# Output: Login Succeeded

Key point: The username is ALWAYS AWS (uppercase). The password is the temporary token from get-login-password. Never hard-code credentials in a Dockerfile or docker-compose file.

Tag and push the image

# Build the image (or use an image you already built)
docker build -t myapp:1.0 .

# Tag with the ECR URI
REPO_URI="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/myapp"

docker tag myapp:1.0 ${REPO_URI}:1.0
docker tag myapp:1.0 ${REPO_URI}:latest

# Push to ECR
docker push ${REPO_URI}:1.0
docker push ${REPO_URI}:latest

# Check the pushed images
aws ecr list-images --repository-name myapp --region ${AWS_REGION}

ECR Lifecycle Policy — automatically clean up old images

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Keep at most 10 tagged images",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": ["v"],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 2,
      "description": "Delete untagged images after 7 days",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 7
      },
      "action": { "type": "expire" }
    }
  ]
}

2. Amazon ECS — Architecture Overview

┌─────────────────────────────────────────────────────────┐│AmazonECSCluster││││┌──────────────────────────────────────────────────┐│││ECSService(desiredcount=2)││││┌──────────────────┐┌──────────────────┐│││││Task1││Task2││││││┌─────────────┐││┌─────────────┐│││││││Container││││Container││││││││(myapp:1.0)││││(myapp:1.0)│││││││└─────────────┘││└─────────────┘││││││││││││││Launch:Fargate││Launch:Fargate│││││└──────────────────┘└──────────────────┘│││└──────────────────────────────────────────────────┘│││││┌──────▼──────┐│││ALB│←internettraffic││└─────────────┘│└─────────────────────────────────────────────────────────┘

ECS concepts

ConceptDescription
ClusterLogical grouping of tasks/services
Task DefinitionBlueprint describing the container(s): image, CPU, memory, env vars, ports
TaskA running instance of a Task Definition
ServiceKeeps N tasks running at all times, integrates with ALB, rolling updates
Launch TypeEC2 (you manage) or Fargate (AWS manages)

3. ECS Launch Type: EC2 vs Fargate

EC2LaunchTypeFargateLaunchType──────────────────────────────────────────────────┌─────────────────────┐┌────────────────────────┐│EC2instances││AWSmanagedcompute││(youmanage)││(noEC2visible)││┌─────────────┐││┌────────────────┐│││ECSAgent││││Task(vCPU/GB)││││───────────││││─────────────││││TaskA││││Container││││TaskB│││└────────────────┘││└─────────────┘│└────────────────────────┘└─────────────────────┘
CriterionEC2 Launch TypeFargate
Server managementYou (patch OS, scale)AWS (fully managed)
CostEC2 instance-hours (can use Reserved/Spot)Per task vCPU/GB-hour
Burst flexibilityMust scale the cluster firstScales immediately, no cluster capacity needed
GPUYes (EC2 GPU instances)No (not supported yet)
Windows containersYesYes
Spot tasksYes (EC2 Spot)Yes (Fargate Spot — ~70% cheaper)
Best forLarge steady workloads, GPU needsVariable load, microservices

4. Create an ECS Fargate Service (CLI)

Step 1: Create the Task Definition

# task-definition.json
cat > task-definition.json << 'EOF'
{
  "family": "myapp",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskRole",
  "containerDefinitions": [
    {
      "name": "myapp",
      "image": "123456789012.dkr.ecr.ap-southeast-1.amazonaws.com/myapp:1.0",
      "portMappings": [
        {
          "containerPort": 3000,
          "protocol": "tcp"
        }
      ],
      "environment": [
        { "name": "NODE_ENV", "value": "production" }
      ],
      "secrets": [
        {
          "name": "DATABASE_URL",
          "valueFrom": "arn:aws:secretsmanager:ap-southeast-1:123456789012:secret:myapp/db-url"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/myapp",
          "awslogs-region": "ap-southeast-1",
          "awslogs-stream-prefix": "ecs"
        }
      },
      "healthCheck": {
        "command": ["CMD-SHELL", "wget -qO- http://localhost:3000/health || exit 1"],
        "interval": 30,
        "timeout": 5,
        "retries": 3
      }
    }
  ]
}
EOF

# Register task definition
aws ecs register-task-definition \
  --cli-input-json file://task-definition.json \
  --region ap-southeast-1

Step 2: Create the CloudWatch Log Group

aws logs create-log-group \
  --log-group-name /ecs/myapp \
  --region ap-southeast-1

Step 3: Create the ECS Cluster

aws ecs create-cluster \
  --cluster-name myapp-cluster \
  --region ap-southeast-1

Step 4: Create the ECS Service

# Note: shorthand syntax values must be on ONE line —
# line breaks inside the string can cause AWS CLI parse errors
aws ecs create-service \
  --cluster myapp-cluster \
  --service-name myapp-service \
  --task-definition myapp:1 \
  --desired-count 2 \
  --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-abc123,subnet-def456],securityGroups=[sg-xyz789],assignPublicIp=ENABLED}" \
  --load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:ap-southeast-1:123456789012:targetgroup/myapp-tg/1234567890abcdef,containerName=myapp,containerPort=3000" \
  --region ap-southeast-1

Required IAM Roles

ecsTaskExecutionRole — for the ECS agent:
  - ecr:GetAuthorizationToken       ← pull images from ECR
  - ecr:BatchGetImage
  - ecr:GetDownloadUrlForLayer
  - logs:CreateLogStream            ← write CloudWatch Logs
  - logs:PutLogEvents
  - secretsmanager:GetSecretValue   ← fetch secrets

ecsTaskRole — for the app code in the container:
  - Permissions the app needs (S3, DynamoDB, etc.) — depends on the application

5. Updating the service — Rolling deployment

# 1. Push the new image to ECR
docker build -t myapp:1.1 .
docker tag myapp:1.1 ${REPO_URI}:1.1
docker push ${REPO_URI}:1.1

# 2. Register a new task definition (change the image tag)
# Edit task-definition.json: image → myapp:1.1
aws ecs register-task-definition \
  --cli-input-json file://task-definition.json

# 3. Update the service — ECS performs a rolling deploy (myapp:2 = new revision)
aws ecs update-service \
  --cluster myapp-cluster \
  --service myapp-service \
  --task-definition myapp:2 \
  --region ap-southeast-1

# 4. Watch the deployment
aws ecs describe-services \
  --cluster myapp-cluster \
  --services myapp-service \
  --query 'services[0].deployments'

6. ECS vs EKS — when to choose which?

ECSEKS──────────────────────────────────────────────────────AWS-native,simplerKubernetes—industrystandardFewerconceptsMoreabstractionsDeepAWSintegration(ALB,IAM,Kubernetesecosystem(Helm,CloudWatch)Prometheus,ArgoCD,KEDA)NoKubernetesknowledgeneededRequireslearningKubernetesHardertomigratetoothercloudsMulti-cloud/hybridfriendlyFreecontrolplaneEKS:$0.10/hourpercluster(~$72/month)

Choose ECS when: small team, no Kubernetes expertise, AWS-only, tight budget.

Choose EKS when: the team already has Kubernetes knowledge, you need Helm/service mesh, a multi-cloud strategy, or advanced autoscaling (KEDA, Karpenter).

Part 2: Security and Image Optimization

1. Optimizing image size

Why does it matter?

  • Pull time: smaller image → faster deploys (important when scaling out)
  • Attack surface: fewer packages → fewer CVEs
  • Storage cost: ECR charges per GB
  • Cold start: Fargate pulls the image when a task starts — a smaller image reduces cold start

Measuring image size

docker images myapp
# REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
# myapp        latest    abc123         1 min ago     1.2GB   ← BEFORE optimization

docker history myapp:latest   # see how much each layer takes

Technique 1: Choose a smaller base image

# BEFORE: full image
FROM python:3.12         # ~1 GB

# AFTER: slim
FROM python:3.12-slim    # ~130 MB

# AFTER: alpine
FROM python:3.12-alpine  # ~55 MB (note: musl libc instead of glibc — some native C libs may not be compatible)

# AFTER: distroless (no shell — very secure)
FROM gcr.io/distroless/python3-debian12   # ~50 MB, no /bin/sh

Technique 2: Clean the apt/apk cache in the same RUN layer

# WRONG: deleting in a different layer — saves no space
RUN apt-get update && apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*   # separate layer — does NOT work

# RIGHT: everything in one RUN
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl && \
    rm -rf /var/lib/apt/lists/*

Technique 3: Multi-stage build (see Day 2, Part 1 again)

# Builder: has all the tools needed to compile
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci                    # installs devDependencies too
COPY . .
RUN npm run build             # compile TypeScript
RUN npm prune --omit=dev      # drop devDependencies from node_modules

# Runtime: only needs the artifacts
FROM node:24-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
# No .ts sources, test files, or devDeps

Technique 4: A thorough .dockerignore

# .dockerignore — list everything not needed at runtime
.git
.github
.gitignore
node_modules
dist
build
*.log
.env*
tests/
docs/
*.md
Dockerfile*
docker-compose*
.eslintrc*
.prettierrc*
coverage/
.nyc_output/

Optimization results compared

TechniqueSize
node:24 base~1.1 GB
node:24-alpine base~180 MB
node:24-alpine + cleanup~165 MB
Multi-stage (alpine runtime)~90 MB
Multi-stage + distroless~65 MB

2. Vulnerability Scanning

#InstallTrivybrewinstalltrivy#macOS#orcurl-sfLhttps://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh|sh#Scanalocalimagetrivyimagemyapp:latest#ShowonlyHIGHandCRITICALCVEstrivyimage--severityHIGH,CRITICALmyapp:latest#Tableoutput(default)#┌─────────────────┬───────────────┬──────────┬────────┬────────────┐#│Library│Vulnerability│Severity│Status│FixedIn│#├─────────────────┼───────────────┼──────────┼────────┼────────────┤#│openssl│CVE-2024-xxxx│HIGH│fixed│3.1.4│#└─────────────────┴───────────────┴──────────┴────────┴────────────┘#ScanaDockerfile(misconfigurationcheck)trivyconfigDockerfile#JSONoutputforaCIpipelinetrivyimage--formatjson--outputresults.jsonmyapp:latest#ScaninCI:failthepipelineifthereisaCRITICALCVEtrivyimage--exit-code1--severityCRITICALmyapp:latest

Amazon ECR Enhanced Scanning (Inspector)

# Enable enhanced scanning for the whole registry
aws ecr put-registry-scanning-configuration \
  --scan-type ENHANCED \
  --rules '[{
    "repositoryFilters": [{"filter":"*","filterType":"WILDCARD"}],
    "scanFrequency": "CONTINUOUS_SCAN"
  }]' \
  --region ap-southeast-1

# CONTINUOUS_SCAN: scans automatically on push + rescans when the CVE database is updated
# SCAN_ON_PUSH: scans only on push (cheaper but not real-time)

# View scan results
aws ecr describe-image-scan-findings \
  --repository-name myapp \
  --image-id imageTag=latest \
  --region ap-southeast-1

3. Non-root User

Why does it matter?

If a container escape happens (an attacker breaks out of the container), a process running as root in the container is equivalent to root on the host (in some configurations). A non-root user significantly reduces the blast radius.

Implementation

# Node.js — the official image already has a "node" user (uid=1000)
FROM node:24-alpine
WORKDIR /app
COPY --chown=node:node package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .

# Switch to non-root BEFORE CMD
USER node
EXPOSE 3000
CMD ["node", "server.js"]
# Python — create a new user
FROM python:3.12-slim
WORKDIR /app

# Create the user/group (set gid/uid explicitly for reproducibility)
RUN groupadd -r -g 1001 appgroup && useradd -r -g appgroup -u 1001 appuser

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY --chown=appuser:appgroup . .

USER appuser
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
# Alpine Linux — use adduser/addgroup (different syntax from Debian)
FROM node:24-alpine
RUN addgroup -S -g 1001 appgroup && adduser -S -G appgroup -u 1001 appuser
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser

Verify non-root

docker run --rm myapp whoami
# appuser   ← not root

docker run --rm myapp id
# uid=1001(appuser) gid=1001(appgroup)

4. Secrets Management — NEVER bake them into the image

The problem: secrets in the Dockerfile/image

# NEVER do this
ENV DATABASE_PASSWORD=mysecret123    # stored in the image layers

ARG API_KEY=sk-abc123
RUN curl -H "Authorization: Bearer ${API_KEY}" ...
# The ARG value is still stored in the layer history!
# Anyone can extract the secrets
docker history my-image --no-trunc
docker inspect my-image | grep -i password

Solution 1: Environment variables at runtime

# Pass them in at docker run
docker run -e DATABASE_URL="postgres://..." myapp

# Or from a file (do not commit this file)
docker run --env-file .env.production myapp

Solution 2: AWS Secrets Manager + ECS

The Task Definition pulls the secret from Secrets Manager:

"secrets": [
  {
    "name": "DATABASE_PASSWORD",
    "valueFrom": "arn:aws:secretsmanager:ap-southeast-1:123456:secret:myapp/db-password"
  },
  {
    "name": "API_KEY",
    "valueFrom": "arn:aws:secretsmanager:ap-southeast-1:123456:secret:myapp/api-key:api_key::"
  }
]

The ECS agent injects the secret into the container's env vars when the task starts. It is never stored in the image or in plaintext in the task definition.

Solution 3: Docker BuildKit secret mount (build-time only)

# Read the secret in RUN but do NOT store it in a layer
RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) \
    npm install
# Build with the secret
docker build \
  --secret id=npm_token,src=$HOME/.npmrc \
  .

The secret exists only during the build and is not stored in the image.

5. SBOM — Software Bill of Materials

An SBOM is a list of all components/packages in an image: OS packages, language libraries, licenses. It has been increasingly required in Enterprise/Government since 2022.

# Generate an SBOM with Syft (from Anchore)
brew install syft

syft myapp:latest
# outputs a list of all packages

# Export as SPDX (a popular standard)
syft myapp:latest -o spdx-json > sbom.spdx.json

# Export as CycloneDX
syft myapp:latest -o cyclonedx-json > sbom.cyclonedx.json

# ECR supports OCI artifacts — you can push the SBOM alongside the image, for example:
docker buildx build --attest type=sbom -t myapp:latest --push .
# or attach a pre-generated SBOM with ORAS: oras attach ...

6. Consolidated Security Checklist

IMAGE BUILD
[ ] Use a base image with a specific tag (no :latest for the base)
[ ] Base image is slim/alpine where possible
[ ] .dockerignore excludes .env, .git, node_modules, test files
[ ] Multi-stage build — no build tools left in the runtime image
[ ] No secrets (passwords, API keys, tokens) baked into the image
[ ] ARG secrets use BuildKit --mount=type=secret
[ ] RUN apt/apk cleanup in the same layer as the install
[ ] COPY --chown= with the correct ownership for the non-root user

RUNTIME
[ ] USER non-root (uid >= 1000)
[ ] EXPOSE documents the port — do not expose unnecessary ports
[ ] read-only root filesystem if the app does not need to write
    (docker run --read-only / ECS readonlyRootFilesystem: true)
[ ] Healthcheck defined in the Task Definition or Dockerfile
[ ] Resource limits (CPU/memory) in the Task Definition

REGISTRY / DEPLOYMENT
[ ] ECR image scanning enabled (ENHANCED if needed)
[ ] Lifecycle policy — automatically delete old images
[ ] Secrets via Secrets Manager / Parameter Store, not plaintext env
[ ] ecsTaskRole has a least-privilege IAM policy
[ ] CloudWatch Logs for container stdout/stderr
[ ] Network: security group allows only the necessary inbound traffic

Review Questions

  1. What is the username in the docker login command for ECR always?

    Show answer

    It is always AWS (uppercase). The password is the temporary token from aws ecr get-login-password. The full command: aws ecr get-login-password --region ... | docker login --username AWS --password-stdin <registry-uri>. The token is valid for 12 hours.

  2. Why do you have to use aws ecr get-login-password instead of a fixed username/password?

    Show answer

    ECR has no fixed username/password. Instead, authentication is based on IAM — the token is generated from your current IAM credentials and is valid for 12 hours. This ensures: (1) no static registry credentials to manage, (2) access is controlled by IAM policies, (3) the token expires on its own, reducing the risk if it leaks.

  3. What is the difference between ecsTaskExecutionRole and ecsTaskRole?

    Show answer

    ecsTaskExecutionRole is used by the ECS agent (not the app): it is needed to pull images from ECR, write logs to CloudWatch, and fetch secrets from Secrets Manager when starting the task. ecsTaskRole is used by the code in the container: the AWS API calls the app needs (S3, DynamoDB, SQS...) at runtime. The two roles have clearly separated responsibilities, following least privilege.

  4. How much does Fargate Spot save compared to Fargate on-demand?

    Show answer

    Fargate Spot saves about ~70% compared to Fargate on-demand. AWS can reclaim capacity when needed, so Fargate Spot fits fault-tolerant workloads such as batch jobs, data processing, and CI/CD tasks — not production web servers that require high availability.

  5. Why does an ECS Task Definition need networkMode: awsvpc when using Fargate?

    Show answer

    Fargate only supports the awsvpc network mode. Each Fargate task gets its own ENI (Elastic Network Interface) with a private IP in the VPC — just like an EC2 instance. This lets you attach a Security Group directly to the task (not the instance), control traffic at the task level, and integrate with VPC networking (subnets, route tables, VPC endpoints).

  6. Why does rm -rf /var/lib/apt/lists/* in a separate RUN layer NOT reduce image size?

    Show answer

    A Docker image is a stack of immutable layers. The earlier layer already wrote /var/lib/apt/lists/ into the filesystem — a later layer can "delete" it from the container's view, but the data still exists in the old layer inside the image. To actually reduce the size, you must delete in the same RUN instruction: RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*.

  7. What is the difference between ECR Basic Scanning and Enhanced Scanning (Inspector)?

    Show answer

    Basic Scanning (the current version uses AWS-native scanning technology — previously based on the open-source Clair) scans only OS packages, and runs on push (scan on push) or as a manual scan (at most once per day per image). Enhanced Scanning (Amazon Inspector) scans both OS packages and language-specific packages (npm, pip, maven...), supports CONTINUOUS_SCAN (automatic rescans when the CVE database is updated), and sends findings to AWS Security Hub. Enhanced Scanning is more detailed and closer to real time but costs extra.

  8. When a container running a root process is compromised, why is it more dangerous than a non-root one?

    Show answer

    If an attacker escapes the container (a container breakout vulnerability), a root process in the container can be equivalent to root on the host OS in some configurations (missing seccomp, AppArmor, user namespaces). Root in the container can also read/write bind-mounted volumes, escalate privileges via SUID binaries, or manipulate the host network. A non-root process (uid >= 1000) significantly reduces the blast radius, though you still need other security layers.

  9. ARG API_KEY=secret in a Dockerfile — is this secret safe? Why?

    Show answer

    It is not safe. Even though ARG exists only at build time, the ARG value is still stored in the image metadata and build history. docker history my-image --no-trunc or docker inspect will show the ARG value. Anyone who has the image can extract the secret. The correct solution: use Docker BuildKit secret mounts (RUN --mount=type=secret,id=my_secret ...) — the secret exists only during the RUN and is not stored in a layer.

  10. Name 3 ways to pass secrets into a container at runtime without storing them in the image.

Show answer

(1) Environment variables at runtime: docker run -e DB_PASSWORD=xxx or --env-file .env.prod — not baked into the image, they only exist in the process environment.

(2) AWS Secrets Manager + ECS secrets: the Task Definition declares "secrets": [{"name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:..."}] — the ECS agent injects them into the container at start, never through the image.

(3) Docker Compose secrets or Docker Swarm secrets: mount the secret as a file under /run/secrets/ in the container, never written to an image layer. With Swarm the file lives in a tmpfs (memory only); with plain Compose (no Swarm) it is a bind mount of a host file, so the file still sits on the host disk.

Hands-on Exercises

Part 1: Amazon ECR and Deploying to ECS Fargate

# Prerequisites: AWS CLI configured, with ECR + ECS permissions

# 1. Create the ECR repo
AWS_REGION=ap-southeast-1
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
REPO_NAME=my-docker-demo

aws ecr create-repository \
  --repository-name ${REPO_NAME} \
  --region ${AWS_REGION}

# 2. Authenticate to ECR
aws ecr get-login-password --region ${AWS_REGION} | \
  docker login --username AWS --password-stdin \
  ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com

# 3. Build and push the image
docker build -t ${REPO_NAME}:latest .
docker tag ${REPO_NAME}:latest \
  ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${REPO_NAME}:latest
docker push \
  ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${REPO_NAME}:latest

# 4. Verify
aws ecr describe-images \
  --repository-name ${REPO_NAME} \
  --region ${AWS_REGION}

# 5. (Optional) Delete the repo after the exercise
aws ecr delete-repository \
  --repository-name ${REPO_NAME} \
  --force \
  --region ${AWS_REGION}

Part 2: Security and Image Optimization

# 1. Install Trivy and scan an image
brew install trivy
docker pull python:3.12      # large image, many CVEs
trivy image --severity HIGH,CRITICAL python:3.12

docker pull python:3.12-slim
trivy image --severity HIGH,CRITICAL python:3.12-slim
# Compare the number of CVEs

# 2. Test non-root
cat > Dockerfile.nonroot << 'EOF'
FROM node:24-alpine
RUN addgroup -S appgroup && adduser -S -G appgroup appuser
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
CMD ["whoami"]
EOF

docker build -f Dockerfile.nonroot -t nonroot-test .
docker run --rm nonroot-test    # prints "appuser"

# 3. Check for secret leaks
cat > Dockerfile.badsecret << 'EOF'
FROM alpine
ARG MY_SECRET=default
RUN echo "Secret: ${MY_SECRET}"
EOF

docker build --build-arg MY_SECRET=supersecret -f Dockerfile.badsecret -t badsecret .
docker history badsecret --no-trunc | grep supersecret   # the secret SHOWS UP in the history!

# 4. Trivy scan for Dockerfile misconfigurations
trivy config Dockerfile.badsecret
# Trivy reports the misconfigurations it finds (e.g. missing USER — container runs as root);
# the exact results may vary by version/check

# Clean up
docker rmi nonroot-test badsecret

References


Next lesson →