Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Lab 3.3: push to ECR and deploy to Fargate behind an ALB

Create a private ECR repository with immutable tags and scan on push, push an arm64 image of the Accounts API, deploy it with CDK to ECS on Fargate in private subnets behind an Application Load Balancer, test it, then destroy everything within the hour.

intermediate⏱ 1 h 30 min🟡 Low costDVA-C03SAA-C03

Assumes: .NET 10 LTS · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · AWS CLI v2 · Docker buildx · Region us-east-1 · labs/m03-accounts-api. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Deploy a private ECR repository with immutable tags, scan on push and lifecycle rules from CDK, and read its scan findings.
  • Build and push an arm64 (Graviton) image with docker buildx.
  • Deploy the Accounts API to ECS on Fargate: tasks in private subnets without public IPs, an internet-facing ALB in public subnets, a task role with read-only data access, logs with retention, a deployment circuit breaker, and target tracking scaling.
  • Verify the deployment, read the logs, trigger a scaling or failure scenario, and tear everything down with a tag check.

Prerequisites

  • Deploying to ECS on Fargate, Health checks and Amazon ECR
  • Lab 3.2 — the image builds and runs locally
  • AWS CLI v2 signed in: aws sso login --profile learn-sandbox; export AWS_PROFILE=learn-sandbox
  • Node.js 22 or 24 LTS and the CDK CLI (npm install -g aws-cdk); account bootstrapped once with cdk bootstrap aws://<account>/us-east-1
  • Docker Desktop with buildx (included)

Why this matters in banking

Fargate behind an ALB in private subnets is Harbourline's default shape for new APIs. Each piece is a control an auditor will ask about: images come only from a private registry and are scanned; tags cannot be overwritten (so "v1" in the change record is exactly what ran); tasks have no public IP; the app's permissions are least privilege; logs are retained for a defined time; failed deployments roll back automatically. Doing it once by hand with IaC makes every later conversation with security and audit easier.

The idea in plain language

ECR is your private Docker registry in AWS. ECS is AWS's container orchestrator: you describe a task definition (image, CPU, memory, ports, roles, logs) and a service keeps N copies running. Fargate runs those tasks without you managing servers. The ALB receives HTTP traffic and spreads it across healthy tasks.

Analogy: ECR is the bank's secure stationery store with numbered, sealed packs (immutable tags). The ECS service is the branch manager who makes sure three cashiers are always on duty, replaces any who fall ill (health checks), and calls in more at busy times (scaling). The ALB is the queue system at the door.

Architecture

Security boundary view. Only the ALB is reachable from the internet. Its security group allows port 80 inbound; the task security group allows 8080 only from the ALB's security group (the CDK pattern wires this). Tasks reach AWS APIs through the NAT gateway (and DynamoDB through a free gateway endpoint). The task execution role (pull image, write logs) is separate from the task role (read one table, read one parameter path).

Step-by-step

All commands run from labs/m03-accounts-api in Git Bash unless noted.

Deploy shared data and seed it

export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
cd infra/cdk && cdk deploy HlM03-Shared -c owner=<your-name> && cd ../..
for f in seed/batch-*.json; do aws dynamodb batch-write-item --request-items "file://$f"; done
aws ssm put-parameter --name /hl-m03/accounts-api/Pseudonymisation/Key --type SecureString \
  --value "$(openssl rand -hex 32)" \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m03-accounts-api Key=Environment,Value=learn Key=Owner,Value=<your-name>

Each batch-write-item should return "UnprocessedItems": {}.

Create the repository

cd infra/cdk && cdk deploy HlM03-Registry -c owner=<your-name> && cd ../..
aws ecr describe-repositories --repository-names hl-m03-accounts-api \
  --query "repositories[0].[imageTagMutability,imageScanningConfiguration.scanOnPush]"

Expected: ["IMMUTABLE", true].

Build and push an arm64 image

ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
REGISTRY=$ACCOUNT.dkr.ecr.us-east-1.amazonaws.com
aws ecr get-login-password | docker login --username AWS --password-stdin $REGISTRY
docker buildx build --platform linux/arm64 -t $REGISTRY/hl-m03-accounts-api:v1 --push .

Try pushing v1 again after a trivial change: ECR rejects it (tag invalid: The image tag 'v1' already exists ... cannot be overwritten because the repository is immutable). That is the control working.

Read the scan results

aws ecr wait image-scan-complete --repository-name hl-m03-accounts-api --image-id imageTag=v1
aws ecr describe-image-scan-findings --repository-name hl-m03-accounts-api --image-id imageTag=v1 \
  --query "imageScanFindings.findingSeverityCounts"

A chiseled image typically shows few or no findings. Anything CRITICAL or HIGH would block a Harbourline release until triaged.

Deploy the Fargate stack

cd infra/cdk
cdk diff HlM03-Fargate -c owner=<your-name> -c imageTag=v1     # review IAM and security group changes
cdk deploy HlM03-Fargate -c owner=<your-name> -c imageTag=v1

CDK prints the IAM and security group changes and asks for confirmation. Deployment takes about 5–8 minutes (VPC, NAT gateway, ALB, service). The output HlM03-Fargate.ApiUrl is the ALB URL. cdk-nag v3 runs at synth time; every acknowledged finding has a written reason in FargateStack.cs.

Test it

API=$(aws cloudformation describe-stacks --stack-name HlM03-Fargate \
  --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text)
curl -i $API/health/ready
curl -s $API/v1/accounts/ACC-0000000001
curl -s "$API/v1/accounts/ACC-0000000001/transactions?limit=3"
curl -i $API/v1/accounts/ACC-9999999999

Note the X-Correlation-ID header: behind the ALB it is the Root= value of X-Amzn-Trace-Id (format 1-xxxxxxxx-...).

Look inside

aws logs tail /hl-m03/accounts-api/ecs --since 10m
aws ecs describe-services --cluster hl-m03-cluster --services hl-m03-accounts-api \
  --query "services[0].[desiredCount,runningCount,deployments[0].rolloutState]"
aws elbv2 describe-target-health --target-group-arn $(aws elbv2 describe-target-groups \
  --query "TargetGroups[?contains(TargetGroupName,'HlM03')].TargetGroupArn | [0]" --output text)

Optional: watch the circuit breaker

Push a deliberately broken image as v2 (for example set ENV Repository__TableName=does-not-exist in a copy of the Dockerfile, so readiness fails), deploy with -c imageTag=v2, and watch ECS events: new tasks fail health checks, the circuit breaker trips and the service rolls back to v1 automatically. The stack update reports failure. Redeploy -c imageTag=v1 to bring CloudFormation back in sync.

Tear down (do not skip)

See Cost and cleanup below. Aim to finish within the hour.

Expected output

$ curl -i $API/health/ready
HTTP/1.1 200 OK
Content-Type: application/json
X-Correlation-ID: 1-67a3f2c1-0f1e2d3c4b5a69788796a5b4

{"status":"Healthy","checks":{"repository":"Healthy"},"durationMs":7.9}

$ aws ecs describe-services ...
[ 1, 1, "COMPLETED" ]

The readiness check now takes a few milliseconds because it calls DynamoDB DescribeTable through the gateway endpoint.

What the CDK stack configures (and why)

Setting in FargateStack.csPurpose
Vpc with MaxAzs = 2, public + PRIVATE_WITH_EGRESS subnets, NatGateways = 1ALB in public subnets, tasks in private ones; one NAT gateway to save cost (⚠ single-AZ egress: production uses one per AZ or VPC endpoints)
AddFlowLog(... REJECT) with 1-week retentionEvidence of blocked traffic, at low cost
AddGatewayEndpoint(DYNAMODB)Free; DynamoDB traffic avoids NAT charges and stays on the AWS network
ContainerInsightsV2 = ENABLEDTask-level CPU/memory metrics for scaling analysis (has a cost; see below)
Task role: GetItem, Query, DescribeTable on one table + its indexes; GetParametersByPath on one pathLeast privilege for the application
LogGroup with ONE_WEEK retention, DESTROYNever-expire logs avoided; teardown leaves nothing
Cpu = 256, MemoryLimitMiB = 512, CpuArchitecture = ARM64Smallest Fargate size; Graviton is cheaper per vCPU-hour
AssignPublicIp = false, TaskSubnets = PRIVATE_WITH_EGRESSNo direct internet exposure for tasks
CircuitBreaker = { Enable, Rollback }Failed deployments roll back automatically
HealthCheckGracePeriod = 60 s, ALB check /health/ready every 15 s, 2 healthy / 3 unhealthyTime for .NET to start; fast enough detection without flapping
deregistration_delay = 30 sIn-flight requests drain quickly during deployments
AutoScaleTaskCount(1..3) + CPU target 60%Target tracking with a hard maximum
Environment: Auth__Mode=Disabled + override⚠ Learning shortcut; see below

Security considerations

⚠ Learning shortcut — not for production

The ALB listens on HTTP port 80 without TLS, has no WAF, no access logs, and the API runs with authentication disabled (explicit override). It serves fictional data and must be destroyed the same hour. Production: HTTPS listener with an ACM certificate (and redirect 80→443), AWS WAF with managed rule groups and rate limiting, ALB access logs to a locked-down S3 bucket, Auth__Mode=Cognito with issuer and client IDs, a NAT gateway per AZ or VPC interface endpoints for ECR, Logs and SSM, and enhanced (Amazon Inspector) image scanning.

  • Immutable tags make the deployed artefact traceable; combine with image signing for a stronger supply-chain story.
  • The task role is not the execution role. If the app gets AccessDenied from DynamoDB, fix the task role; if the task cannot pull the image or write logs, fix the execution role.
  • No SSH, no exec by default. Debug with logs and metrics; enable ECS Exec only temporarily and with logging if you must.

Troubleshooting

SymptomLikely causeFix
cdk deploy fails: This stack uses assets ... bootstrapAccount/Region not bootstrappedcdk bootstrap aws://<account>/us-east-1
cdk-nag validation report fails synthA new finding without an acknowledgmentFix the resource, or add an Acknowledgment with the exact finding ID and a reason
Tasks stop with CannotPullContainerErrorTag not pushed, wrong Region, or no route to ECRaws ecr list-images; confirm the NAT gateway and private route tables
exec format error / exit 139amd64 image on ARM64 tasksBuild with --platform linux/arm64
Tasks start then are killed, targets "unhealthy"/health/ready fails: table missing, wrong Region, missing parameterRead /hl-m03/accounts-api/ecs logs; check step 1
App exits with Configure Pseudonymisation:KeyParameter not created or wrong pathCreate /hl-m03/accounts-api/Pseudonymisation/Key
502 from the ALB right after deployNo healthy targets yetWait for the grace period; check target health
503 from the ALBZero registered targets (service scaled to 0 or all failing)describe-services events
Stack stuck UPDATE_IN_PROGRESSCircuit breaker rolling back, or tasks never stabiliseWatch ECS service events; it times out or rolls back

Cost and cleanup

Approximate us-east-1 costs while running (⚠ VERIFY current prices on the AWS pricing pages before you start):

ResourceApprox. per hour
NAT gatewayUSD 0.045 + USD 0.045 per GB processed
Application Load Balancerabout USD 0.0225 + LCU usage (tiny for lab traffic)
Public IPv4 addresses (ALB in 2 AZs + NAT)USD 0.005 each
Fargate arm64, 0.25 vCPU + 0.5 GB, 1 taskabout USD 0.01
Container Insights, flow logs, CloudWatch Logs, DynamoDB on-demand, ECR storagecents for a one-hour lab
Totalroughly USD 0.10 per hour; under USD 0.25 if destroyed within the hour

Free alternative: Lab 3.2 locally, plus cdk synth (no deployment) to inspect the generated CloudFormation and the cdk-nag report.

cd infra/cdk
cdk destroy HlM03-Fargate HlM03-Registry HlM03-Shared -c owner=<your-name> --force
aws ssm delete-parameter --name /hl-m03/accounts-api/Pseudonymisation/Key

# Confirm nothing tagged for this lab remains (deleted resources can take a few minutes to disappear)
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m03-accounts-api \
  --query "ResourceTagMappingList[].ResourceARN"
# Belt and braces: no NAT gateways or load balancers left
aws ec2 describe-nat-gateways --filter Name=state,Values=available --query "NatGateways[].NatGatewayId"
aws elbv2 describe-load-balancers --query "LoadBalancers[].LoadBalancerName"

The registry stack uses EmptyOnDelete, so the repository is deleted with its images.

Exercises

  • 🟢 Guided: Scale the service to 2 tasks with aws ecs update-service --cluster hl-m03-cluster --service hl-m03-accounts-api --desired-count 2, call the API 20 times and confirm both tasks log requests (aws logs tail shows two stream names).
  • 🟡 Challenge: Change the scaling policy in FargateStack.cs to ScaleOnRequestCount (requests per target), redeploy, and generate load with a loop of curl calls. Find the scaling activity in aws application-autoscaling describe-scaling-activities --service-namespace ecs.
  • 🔴 Live problem: After a deployment, half of the requests fail with 502 for about 20 seconds, then everything is fine. Logs show tasks being stopped while still handling requests. What settings do you investigate?

Solutions

Knowledge check

Certification practice

Completion checklist

  • ECR repository is immutable with scan on push; I read the scan findings
  • The arm64 image ran on Fargate in private subnets and answered through the ALB
  • I saw logs in /hl-m03/accounts-api/ecs with correlation IDs
  • I destroyed all stacks, deleted the parameter and the tag check returned nothing

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page