HANDS-ON LAB Intermediate

Deploying ECR Containers to AWS ECS Fargate: Logging, Healthchecks & Rollback

Hands-on guide to serverless container deployment on ECS Fargate with CloudWatch logs, target group healthchecks, and zero-downtime rollouts.

Vibe DevOps·· ~6 min read
AWS CLIECS FargateECRCloudWatch Logsjq

Key Takeaways & Prerequisites

  • AWS Fargate eliminates EC2 server management, patching, and OS maintenance by running containers in isolated serverless compute environments.
  • Deploy an Application Load Balancer (ALB) across multiple public subnets while isolating Fargate tasks inside private subnets without public IPs.
  • Separate IAM Execution Role (pulling ECR images and logging to CloudWatch) from Task Role (permissions used by your application code).
  • Configure target group health checks and rolling deployment minimumHealthyPercent to guarantee zero-downtime application updates.

Architecture & Execution Flow

  1. 01 →VPC & Subnet IsolationPublic ALB, Private Fargate Tasks
  2. 02 →Dual IAM RolesExecution Role vs Application Task Role
  3. 03 →ECS Task DefinitionContainer sizing, logs, environments
  4. 04 →Rolling UpdateZero-downtime deployment via ALB
Table of Contents

Scope and Prerequisites

This is an operational lab guide, not yet executed against a live AWS account; no actual deployment telemetry or outputs are included. The objective: deploy a single HTTP container with centralized logging and verifiable rollback capabilities. Do not deploy this architecture to production: it lacks TLS termination, load balancing, and high availability redundancy.

Prerequisites: AWS CLI v2, Bash, jq, curl; authenticate via an AWS IAM Identity Center (SSO) profile using an organization-approved role. The deploying identity requires permissions to manage ECS, read ECR/EC2, administer the designated lab CloudWatch log group, and execute iam:PassRole strictly scoped to the execution role defined below, enforcing iam:PassedToService = ecs-tasks.amazonaws.com. Coordinate with your IAM administrator if you lack these privileges; avoid broad administrative grants such as AdministratorAccess.

You must provide an existing container image hosted in an ECR repository within the same account and region, compiled for Linux amd64, listening on 0.0.0.0:8080, returning HTTP 200 at /health, packaging Python 3 with urllib.request, and streaming logs to stdout/stderr. You can source an image from the GitHub Actions OIDC → ECR pipeline, though this lab does not depend on that workflow. If pushing manually, follow the official ECR documentation.[8]

Utilize a pre-existing dedicated lab VPC: a public subnet with a default route 0.0.0.0/0 → Internet Gateway, functional DNS resolution, and NACLs permitting return traffic. A dedicated security group must strictly restrict inbound TCP 8080 to your current /32 IPv4 address, with egress allowing HTTPS 443 for ECR and CloudWatch Logs. Assigning a public IP enables the task to reach outbound endpoints directly without requiring a NAT Gateway.[3] Deploying to a private subnet requires either a NAT Gateway or interface/gateway VPC endpoints for ECR API, ECR DKR, S3, and CloudWatch Logs—simply disabling public IP assignment will break connectivity.

1. Environment and Variable Declaration

Populate actual resource identifiers from the AWS Management Console; do not copy placeholder IDs. Choose a unique lab namespace; if a resource with the same name already exists, halt execution and audit ownership.

export AWS_PROFILE=lab-sso
export AWS_REGION=ap-southeast-1
aws sso login --profile "$AWS_PROFILE"
aws sts get-caller-identity
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
LAB=ecs-http-lab-20261021
REPO=your-existing-lab-repository
TAG=REPLACE_WITH_EXISTING_TAG_OR_COMMIT_SHA
SUBNET=subnet-REPLACE
SG=sg-REPLACE
LOG_GROUP=/ecs/$LAB
ROLE_NAME=$LAB-execution
EXEC_ROLE=arn:aws:iam::$ACCOUNT:role/$ROLE_NAME
DIGEST=$(aws ecr describe-images --repository-name "$REPO" \
  --image-ids imageTag="$TAG" --query 'imageDetails[0].imageDigest' --output text)
IMAGE=$ACCOUNT.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO@$DIGEST
aws ec2 describe-subnets --subnet-ids "$SUBNET"
aws ec2 describe-security-groups --group-ids "$SG"

Reconcile account ID, VPC ID, and the /32 ingress rule before proceeding. Referencing an immutable image digest prevents unintended mutations caused by tag overwrites.

2. Execution Role and CloudWatch Logs

The task execution role grants the ECS container agent permission to pull container images and publish logs; the task role is reserved for application-level AWS API calls. Because this lab application does not interact with AWS services, omit taskRoleArn.[2]

In IAM Console → Roles → Create role → Custom trust policy, paste the following JSON; name the role $ROLE_NAME using the resolved variable. Do not attach broad AWS managed policies. Create an inline permissions policy in the subsequent step.[2]

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "ecs-tasks.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }]
}

In IAM → selected role → Add permissions → Create inline policy → JSON. Substitute ACCOUNT, REGION, REPO, and LAB with real values; only GetAuthorizationToken requires resource *.[2]

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ecr:GetAuthorizationToken",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": ["ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage"],
      "Resource": "arn:aws:ecr:REGION:ACCOUNT:repository/REPO"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:REGION:ACCOUNT:log-group:/ecs/LAB:log-stream:*"
    }
  ]
}

Name the inline policy lab-pull-and-logs. Pre-create the log group so the execution role does not require logs:CreateLogGroup. The awslogs log driver captures stdout/stderr; it does not tail arbitrary log files inside the container filesystem.[6]

aws logs create-log-group --log-group-name "$LOG_GROUP"
aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 1
aws ecs create-cluster --cluster-name "$LAB"

3. Register Task Definition and Provision Service

AWS Fargate requires the awsvpc network mode; 256 CPU units / 512 MiB is a valid Linux configuration pair. Specify X86_64 to match the amd64 architecture.[1] Health checks execute inside the container namespace, requiring the python binary within the image. This example leverages the Python application referenced in the CI guide linked above, eliminating dependencies on a curl binary in the image.[5]

jq -n --arg family "$LAB" --arg image "$IMAGE" \
  --arg role "$EXEC_ROLE" --arg region "$AWS_REGION" --arg logs "$LOG_GROUP" '
{
  family: $family,
  networkMode: "awsvpc",
  requiresCompatibilities: ["FARGATE"],
  cpu: "256", memory: "512",
  runtimePlatform: {operatingSystemFamily: "LINUX", cpuArchitecture: "X86_64"},
  executionRoleArn: $role,
  containerDefinitions: [{
    name: "app", image: $image, essential: true,
    portMappings: [{containerPort: 8080, protocol: "tcp"}],
    healthCheck: {
      command: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen(\"http://127.0.0.1:8080/health\", timeout=2).read()"],
      interval: 15, timeout: 5, retries: 3, startPeriod: 30
    },
    logConfiguration: {
      logDriver: "awslogs",
      options: {"awslogs-group": $logs, "awslogs-region": $region,
                "awslogs-stream-prefix": "app", "mode": "non-blocking",
                "max-buffer-size": "1m"}
    }
  }]
}' > task.json
jq empty task.json
TD=$(aws ecs register-task-definition --cli-input-json file://task.json \
  --query 'taskDefinition.taskDefinitionArn' --output text)
GOOD_TD=$TD
jq -n --arg subnet "$SUBNET" --arg sg "$SG" \
  '{awsvpcConfiguration:{subnets:[$subnet],securityGroups:[$sg],assignPublicIp:"ENABLED"}}' > network.json
aws ecs create-service --cluster "$LAB" --service-name "$LAB" \
  --task-definition "$TD" --desired-count 1 --launch-type FARGATE \
  --platform-version 1.4.0 --network-configuration file://network.json \
  --deployment-configuration 'minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}'
aws ecs wait services-stable --cluster "$LAB" --services "$LAB"

Rolling updates may temporarily run two concurrent tasks, incurring additional compute costs. The deployment circuit breaker can only initiate an automated rollback if a prior deployment reached COMPLETED status; an initial deployment failure has no known-good state to revert to.[4]

4. Verification: Beyond the RUNNING State

aws ecs describe-services --cluster "$LAB" --services "$LAB" \
  --query 'services[0].{deployments:deployments,events:events[0:5]}'
TASK=$(aws ecs list-tasks --cluster "$LAB" --service-name "$LAB" \
  --query 'taskArns[0]' --output text)
aws ecs describe-tasks --cluster "$LAB" --tasks "$TASK" \
  --query 'tasks[0].{status:lastStatus,health:healthStatus,containers:containers}'
ENI=$(aws ecs describe-tasks --cluster "$LAB" --tasks "$TASK" \
  --query 'tasks[0].attachments[0].details[?name==`networkInterfaceId`].value | [0]' --output text)
IP=$(aws ec2 describe-network-interfaces --network-interface-ids "$ENI" \
  --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
curl --fail --max-time 10 "http://$IP:8080/health"
aws logs tail "$LOG_GROUP" --since 10m

Retain GOOD_TD only when the health status reports HEALTHY, the rollout is COMPLETED, HTTP queries succeed, and CloudWatch streams show expected application logs. Issue curl requests only from the allowlisted /32 IP; note that the task's public IP will change upon task replacement.

If the waiter command times out, inspect service events rather than attempting to recreate the service. CannotPullContainerError: verify the image digest, execution role policies, and network egress routing. ResourceInitializationError: check log group existence, CloudWatch permissions, and HTTPS egress. Health check failures: validate the application endpoint, startup latency, and python binary availability. External HTTP timeouts despite a healthy internal status: verify your /32 ingress rule, route tables, NACLs, and public IP mapping.

5. Deploying a New Revision and Rollback

Deploy only newly tested image digests validated locally; avoid mutating tags such as latest. Persist the known-good task definition ARN (GOOD_TD) in your operational notes before switching terminal sessions.

NEW_IMAGE=REPLACE_WITH_FULL_ECR_URI_AT_SHA256_DIGEST
jq --arg image "$NEW_IMAGE" '.containerDefinitions[0].image=$image' task.json > task-next.json
NEXT_TD=$(aws ecs register-task-definition --cli-input-json file://task-next.json \
  --query 'taskDefinition.taskDefinitionArn' --output text)
aws ecs update-service --cluster "$LAB" --service "$LAB" --task-definition "$NEXT_TD"
aws ecs wait services-stable --cluster "$LAB" --services "$LAB"
# In case a manual rollback is required:
aws ecs update-service --cluster "$LAB" --service "$LAB" --task-definition "$GOOD_TD"
aws ecs wait services-stable --cluster "$LAB" --services "$LAB"

Repeat the verification phase against the newly assigned task and IP address. A successful waiter exit does not guarantee that the new revision remains active: the deployment circuit breaker may have executed an automated rollback. Reconcile the active task definition against NEXT_TD or GOOD_TD to confirm expected state.

6. Resource Teardown and Cost Mitigation

Incurred costs include Fargate compute units, public IPv4 address allocations, CloudWatch Logs ingestion/storage, ECR storage, and egress data transfer; do not assume complete Free Tier coverage. NAT Gateways or VPC endpoints—if selected for private subnet architectures—incur hourly and data processing charges.[7] ECR retains container images independently after tasks terminate.

aws ecs update-service --cluster "$LAB" --service "$LAB" --desired-count 0
aws ecs wait services-stable --cluster "$LAB" --services "$LAB"
aws ecs delete-service --cluster "$LAB" --service "$LAB"
aws ecs wait services-inactive --cluster "$LAB" --services "$LAB"
aws ecs delete-cluster --cluster "$LAB"
aws ecs deregister-task-definition --task-definition "$GOOD_TD"
# Execute only if a new revision was registered:
# aws ecs deregister-task-definition --task-definition "$NEXT_TD"
aws logs delete-log-group --log-group-name "$LOG_GROUP"
aws iam delete-role-policy --role-name "$ROLE_NAME" --policy-name lab-pull-and-logs
aws iam delete-role --role-name "$ROLE_NAME"

Verify running tasks using list-tasks; if teardown commands fail, resolve errors until all lab-scoped resources are completely removed. Do not delete pre-existing shared VPCs, subnets, security groups, or baseline ECR repositories. Purge dedicated images or repositories only after confirming no downstream dependencies exist; inspect ECR storage and the AWS Billing console post-lab. Deregistering a task definition revision does not delete the underlying container image.

Sources

[1] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html — AWS task [2] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html — AWS role [3] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-task-networking.html — AWS network [4] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-circuit-breaker.html — AWS rollback [5] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/healthcheck.html — AWS health [6] https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_awslogs.html — AWS logs [7] https://aws.amazon.com/fargate/pricing — AWS price [8] https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html — AWS ecr

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs