This resume is also available in English.

6. Deploying the system6 / 14 · All columns

Columns › 6. Deploying the system › Part 33

Deploying on AWS: Running Container Services on ECS Fargate

在 AWS 上部署:用 ECS Fargate 跑容器服務

Put the shop’s Go services on AWS without running Kubernetes: compare six ways to deploy, explain VPCs, NAT, security groups, the ALB and ECS services and tasks with pictures, then push to ECR, write a task definition, wire up the ALB and graceful shutdown, roll back with the circuit breaker, autoscale, and deploy from GitHub Actions over OIDC.

  • AWS
  • ECS
  • Fargate
  • ALB
  • DevOps
  • Go
In this article
  1. What this article solves
  2. Step 1: Choose a path: six ways to run services on AWS
  3. Step 2: The networking building blocks: VPCs, subnets, NAT and security groups
  4. Step 3: ECS itself: clusters, services, tasks and task definitions
  5. Step 4: Push images to ECR
  6. Step 5: Write the task definition
  7. Step 6: Create the service behind the ALB
  8. Step 7: Deployment and rollback: rolling updates, the circuit breaker, blue-green and canary
  9. Step 8: Autoscaling: on CPU or on requests per task
  10. Step 9: How services call each other
  11. Step 10: The delivery flow: Terraform for the foundations, GitHub Actions for versions
  12. Step 11: Logs, metrics and cost
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Blue-Green and Canary Releases: Doing Them Right and What to Watch For”, covered how to shift traffic to a new version safely, assuming there was already somewhere to run containers. This article answers a more basic question: “How do I deploy on AWS?” AWS offers many ways to run code, from managing your own virtual machines to Lambda, where there is no machine at all. First the six common options are compared side by side, with the situations each one fits; then, with ECS on Fargate as the main path, the shop’s Go services are actually put on it: each building block is explained with a picture first, then built step by step.

What this article solves

So far the shop has run on a single virtual machine, started with the compose.yaml from “Deploying a Whole Microservice System with Docker Compose”. The team has three people, and the setup is starting to hurt:

  • When that machine reboots, the whole shop is down; operating system patches can only happen in the middle of the night.
  • Deploying means SSHing in, pulling images and restarting containers; who deployed which version is only recorded in the chat history.
  • The database password and the payment provider’s key live in a .env file on the machine, and people who have since left have seen it.
  • For the Friday-night flash sale, api-gateway gets ten times its usual requests; the only option is to upgrade the whole machine beforehand and downgrade it afterwards.

The team discussed Kubernetes, but nobody has time to look after a cluster’s add-ons and upgrades. The goal of this article: without touching Kubernetes, use AWS-managed pieces so that the three services api-gateway, order and payment run across Availability Zones, broken replicas are replaced automatically, deployments and rollbacks are safe, and the number of replicas follows traffic. Step by step:

  1. Choosing a path: what EC2, Elastic Beanstalk, ECS Fargate, EKS, Lambda and S3 plus CloudFront each fit, and why the shop picks ECS Fargate.
  2. The networking building blocks: Regions and Availability Zones, VPCs, public and private subnets, NAT gateways and VPC endpoints, security groups, the ALB.
  3. ECS itself: clusters, services, tasks and task definitions, plus two IAM roles that are easy to confuse.
  4. Pushing images to ECR, with a CPU architecture that matches the task definition.
  5. Writing the task definition: CPU and memory, ports, logs, secrets, health checks.
  6. Creating the service behind the ALB: health checks, the stop sequence, and what the Go side has to do.
  7. Deployment and rollback: rolling-update percentages, the deployment circuit breaker, alarm-based rollback, blue-green and canary.
  8. Autoscaling: on CPU or on requests per task.
  9. How services call each other: Service Connect, an internal ALB or Cloud Map.
  10. The delivery flow: Terraform for the foundations, GitHub Actions deploying new versions over OIDC, least privilege.
  11. Logs, metrics and cost: what to watch and where the money goes.

Step 1: Choose a path: six ways to run services on AWS

Leave the details aside for a moment and look only at “how much do you manage, and how much does AWS manage for you”. The further right, the more AWS manages, and the less you can tune:

Option OS and patching Cluster and nodes Deploy and scaling Code or content EC2 instances You You You You Elastic Beanstalk Shared AWS Shared You ECS on Fargate AWS AWS Shared You EKS Shared Shared You You Lambda AWS AWS AWS You S3 + CloudFront AWS AWS AWS You You: fully yours. Shared: AWS gives the mechanism, you choose settings and timing. AWS: managed. The highlighted row is the shop's path: ECS on Fargate.

Figure: from EC2, where you manage the operating system, to Lambda, where you hand over only code; S3 plus CloudFront only serves static files and runs no server code. The shop’s main path is ECS Fargate in the middle.

OptionWhat you manageFitsWhyWhen not to use it
EC2 instances (+ Auto Scaling Group)Operating system, patching, deploy scripts; the unit of scaling is a whole machineLegacy systems not yet containerised, special kernel settings or hardware, large steady monolithsThe most control; with steady load and a Savings Plan, the lowest cost per unit of computeMany small services scaling separately, frequent deploys; nobody on the team wants to manage an operating system
Elastic BeanstalkThe application and platform version settingsA single web application (Java, Python, Node.js, Go or Docker) that needs to go live quicklyBuilds the EC2 instances, Auto Scaling Group and load balancer for youSeveral microservices calling each other, fine control over deployment and networking; it is still EC2 underneath, on its platform-update schedule
ECS on FargateTask definitions and service settings; no machinesA handful to a few dozen containerised services, minimal operations wanted, AWS lock-in acceptableNo nodes to manage; each task gets its own network interface and security group; native ALB, IAM and CloudWatch integrationYou need DaemonSets, Operators or Kubernetes-ecosystem tools, or the same setup across clouds
EKS (Kubernetes)Cluster add-ons, node strategy, Kubernetes resourcesAlready on Kubernetes, many services, GitOps and the Operator ecosystem wantedThe standard Kubernetes API, which largely carries over to other cloudsA small team, few services, nobody owning cluster upgrades
LambdaFunction code and its triggersEvent-driven work, sparse traffic, or tall but short spikes: processing S3 uploads, scheduled batches, receiving webhooksNo requests, no charge; scaling is handled by AWSLong-lived connections (long-running broker subscriptions, a resident connection pool), jobs over 15 minutes, steady high traffic all day
S3 + CloudFrontStatic files and cache rulesStatic front-end sites, single-page applications, documentation sitesNo servers; the CDN answers close to the user; very low costPages that need code running on a server

AWS also used to offer App Runner: give it an image, get an HTTPS URL. It is no longer open to new customers, and AWS recommends ECS Express Mode instead: with only an image, a task execution role and an infrastructure role, it creates a Fargate service, an ALB, an HTTPS certificate and autoscaling for you. What Express Mode creates is still the ECS resources described in this article, with the defaults chosen for you; it is a fine way to get something running, but you still need the following steps to understand what each piece is doing.

Why the shop picks ECS Fargate:

  • Three services, three people. EKS needs someone to own cluster upgrades and add-ons, EC2 needs someone to patch operating systems; Fargate needs neither.
  • Every service is already a container. The Dockerfile and health-check subcommand from “Deploying a Whole Microservice System with Docker Compose” carry over almost unchanged.
  • The services are long-running. order and payment consume events continuously and keep connection pools open, which does not suit Lambda.
  • The front end is handled separately. The shop’s front end is static files on S3 plus CloudFront and takes no containers.

When would this choice change? When the number of services grows to the point where the Kubernetes ecosystem is needed (Operators, a service mesh, KEDA scaling on queues), or when the company wants one deployment method across clouds: that is the time to move to EKS, which is the subject of the next article.

Step 2: The networking building blocks: VPCs, subnets, NAT and security groups

When deploying on AWS, most problems are networking problems. First one picture of the building blocks, then why each one exists:

Internet Region: ap-northeast-1 (Tokyo) enters via the internet gateway VPC 10.30.0.0/16 AZ a Public subnet ALB node NAT gateway Private subnet order task payment task Database subnet RDS primary AZ c Public subnet ALB node NAT gateway Private subnet order task payment task Database subnet RDS standby Regional services ECR CloudWatch Logs Secrets Manager IAM A subnet lives in exactly one AZ; create each kind of subnet once per AZ.

Figure: a Region contains several Availability Zones; the VPC spans the zones and is cut into a public, a private and a database subnet in each zone. ECR, CloudWatch Logs and Secrets Manager are regional services and do not sit in subnets.

In plain words:

  • A Region is a whole set of data centres in one geographic location, such as Tokyo, ap-northeast-1. Most resources belong to a Region; spanning Regions needs its own design.
  • An Availability Zone (AZ) is a group of data centres within a Region with independent power and networking. Spread replicas across two or three zones, and the service survives one zone failing.
  • A VPC is your private network inside a Region, with an address range you choose (for example 10.30.0.0/16).
  • A subnet is a smaller range cut out of the VPC, and each subnet belongs to exactly one Availability Zone. Its route table decides whether it is public or private:
    • A public subnet has a route to the internet gateway, and resources in it can have public IPs. Only the ALB and the NAT gateways go here.
    • A private subnet has no direct route to the internet. Fargate tasks go here: nothing outside can connect in.
    • A database subnet is another set of private subnets holding only RDS, without even an outbound route to the internet.
  • A NAT gateway lets tasks in private subnets “connect out” (calling the payment provider, pulling images) while nothing outside can connect in. It sits in a public subnet; one per Availability Zone avoids a single point of failure.
  • The ALB (Application Load Balancer) is the public HTTP/HTTPS entry point. Its nodes sit in the public subnet of each zone and forward requests, according to rules, to a target group; what is registered in the target group are the private IPs of individual tasks.

The NAT cost trap and VPC endpoints

Besides an hourly charge, a NAT gateway charges a processing fee for every GB that passes through it. If tasks in private subnets pull images, write logs and read secrets through NAT, at high volume this line can stand out more than Fargate itself. The alternative is VPC endpoints: traffic goes over AWS’s internal network straight to the service, without passing through NAT.

NAT gateway only Fargate task private subnet NAT gateway charged per GB Internet AWS services ECR, S3, Logs, secrets Payment provider external API images, logs, secrets, payments NAT gateway + VPC endpoints Fargate task private subnet VPC endpoints ecr.api, ecr.dkr, s3 logs, secretsmanager NAT gateway charged per GB AWS services ECR, S3, Logs, secrets Payment provider external API AWS network external calls only

Figure: on top, all traffic goes through the NAT gateway; below, ECR, S3, CloudWatch Logs and Secrets Manager use VPC endpoints, and only traffic that really has to reach the internet (such as the payment provider) uses NAT.

EndpointTypeWhy it is needed
com.amazonaws.<region>.ecr.apiInterface endpointGetting the ECR login token and image metadata
com.amazonaws.<region>.ecr.dkrInterface endpointThe registry API used to pull images
com.amazonaws.<region>.s3Gateway endpointImage layers are actually stored in S3; gateway endpoints cost nothing extra
com.amazonaws.<region>.logsInterface endpointawslogs writing to CloudWatch Logs
com.amazonaws.<region>.secretsmanagerInterface endpointReading secrets when a task starts

Interface endpoints themselves are charged per hour and per Availability Zone, so more is not always better: for a low-traffic development environment, NAT alone is simpler; in production, with large images and tasks scaling often, ECR and S3 endpoints usually pay for themselves. The shop calls an external payment provider, so NAT cannot go away; the endpoints only stop “traffic to AWS’s own services” from taking the expensive detour.

Security groups: each layer admits only the layer before it

A security group is a firewall attached to a network interface, and its rules can only “allow”. Its most useful property is that a rule’s source can be another security group instead of an IP range: task IPs change every time, but their security groups do not.

Internet any source ALB sg-alb inbound 443 from: anywhere api-gateway sg-gw inbound 8080 from: sg-alb order / payment sg-svc inbound 8080 from: sg-gw RDS sg-db inbound 5432 from: sg-svc Rules name a security group as the source, not IPs: task IPs change every time, groups do not.

Figure: the internet can reach only the ALB on 443; api-gateway accepts 8080 only from the ALB’s security group; order and payment accept connections only from api-gateway; RDS accepts 5432 only from the task security groups.

A chain like this writes “who may connect to whom” into the configuration rather than into IP lists. A common mistake is to let the task security group allow 8080 from 0.0.0.0/0 for convenience; the tasks look safe in a private subnet, but anything else in the same VPC can bypass the ALB and hit them directly.

Step 3: ECS itself: clusters, services, tasks and task definitions

ECS has only four core nouns. Once their relationship is clear, the rest of the configuration is filling in blanks:

Task definition (blueprint) shop-order:41 previous, kept shop-order:42 image, CPU, secrets… Cluster shop-prod Service order desired: 3 tasks ALB target group registers task IPs register Task 1 Fargate 0.5 vCPU / 1 GB Task 2 Fargate 0.5 vCPU / 1 GB Task 3 Fargate 0.5 vCPU / 1 GB Fargate gives each task isolated compute: no machines to manage, billed by the task's size.

Figure: a task definition is a versioned blueprint; a service keeps a given number of tasks running from that blueprint and registers them in a target group; tasks are the running copies, with machines provided by Fargate; a cluster is just a namespace grouping the services.

  • Task definition: a JSON blueprint stating the image, CPU and memory, ports, environment variables, secrets, logging and health check. Every change produces a new revision (shop-order:41, shop-order:42); old revisions are kept, and rolling back means pointing at an old one.
  • Task: one running copy created from a task definition, holding one or more containers. The equivalent of a Kubernetes Pod.
  • Service: “I want 3 order tasks running at all times”. It replaces tasks that die, swaps them according to rules during deployments, can register them with an ALB target group, and can autoscale. The equivalent of a Deployment plus part of a Service.
  • Cluster: a logical grouping of services and tasks. With Fargate there are no machines in it to manage; usually one cluster per environment (shop-prod, shop-staging).
  • Fargate: one kind of ECS “capacity”. AWS gives each task an isolated environment you cannot see, billed per second by the vCPU and memory the task declares. The other kind of capacity is EC2: your own machines join the cluster, and managing them is your job again.

Two IAM roles: the task execution role and the task role

This is the part of ECS that confuses people most. The two roles have different users, used at different times:

Before the container starts (and logging) Task execution role executionRoleArn ECS / Fargate agent used by ECR pull image Secrets Manager read secrets CloudWatch Logs write logs While the program runs Task role taskRoleArn Go program SDK default chain used by S3 settlement files

Figure: the task execution role is for ECS itself: before the container starts it pulls the image, reads secrets and creates the log stream. The task role is for the Go program inside the container: calling AWS APIs such as S3 while it runs.

RoleUsed byWhenWhat the shop needs
Task execution role (executionRoleArn)The ECS/Fargate agentBefore the task starts; log writesPull ECR images, write CloudWatch Logs (the AWS-managed policy AmazonECSTaskExecutionRolePolicy), plus read the shop/prod/* secrets
Task role (taskRoleArn)The program in the container (AWS SDK)While it runsDepends on the service: payment reads the settlement-file path in S3; api-gateway needs no AWS permissions at all

Both roles’ trust policies trust ecs-tasks.amazonaws.com, with conditions so that only ECS in your own account can assume them, which prevents other accounts from borrowing them (the “confused deputy” problem):

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Effect": "Allow",
			"Principal": { "Service": "ecs-tasks.amazonaws.com" },
			"Action": "sts:AssumeRole",
			"Condition": {
				"ArnLike": { "aws:SourceArn": "arn:aws:ecs:ap-northeast-1:111122223333:*" },
				"StringEquals": { "aws:SourceAccount": "111122223333" }
			}
		}
	]
}

On top of the AWS-managed policy, the task execution role gets a policy that can only read the shop’s secrets:

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Effect": "Allow",
			"Action": "secretsmanager:GetSecretValue",
			"Resource": "arn:aws:secretsmanager:ap-northeast-1:111122223333:secret:shop/prod/*"
		}
	]
}

If the secrets are encrypted with your own KMS key, add kms:Decrypt on that key as well. Give each service its own task role (shop-order-task, shop-payment-task) rather than letting the three share one role that can do everything; api-gateway calls no AWS APIs, so it simply gets no task role.

Step 4: Push images to ECR

ECR is AWS’s private image registry. Fargate pulls ECR images using the task execution role, with no separate credentials. Doing it once by hand looks like this; step 10 hands it over to CI:

Schematic: terminal 1 Create repository aws ecr create-repository … IMMUTABLE 2 Log in aws ecr get-login-password | docker login 3 Build for the task's CPU docker buildx build --platform linux/arm64 4 Push -t $REG/shop/order:<SHA> --push 5 Check architecture imagetools inspect → linux/arm64 The platform in step 3 must match runtimePlatform in the task definition.

Figure (schematic): ① create the repository with immutable tags ② log in with a short-lived token ③ build for the task’s CPU architecture ④ push ⑤ check the image’s architecture before putting it in the task definition.

# ① one repository per service; a tag can never be pushed again
aws ecr create-repository --repository-name shop/order \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true

# ② log in (the token is valid for 12 hours)
REG=111122223333.dkr.ecr.ap-northeast-1.amazonaws.com
aws ecr get-login-password --region ap-northeast-1 \
  | docker login --username AWS --password-stdin "$REG"

# ③④ build the arm64 image and push it; the tag is the git commit SHA
SHA="$(git rev-parse --short=12 HEAD)"
docker buildx build --platform linux/arm64 \
  --build-arg SERVICE=order --build-arg VERSION="$SHA" \
  -f deploy/docker/Dockerfile -t "$REG/shop/order:$SHA" --push .

# ⑤ check which architecture was pushed
docker buildx imagetools inspect "$REG/shop/order:$SHA"

The Dockerfile follows the shape from “Deploying a Whole Microservice System with Docker Compose”, adding only cross-compilation:

# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ARG SERVICE TARGETOS TARGETARCH VERSION=dev
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" \
    -o /out/server ./cmd/${SERVICE}

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /app/server
USER nonroot:nonroot
ENTRYPOINT ["/app/server"]
CMD ["serve"]

The architectures must match. Fargate supports x86_64 and ARM64 (Graviton), chosen by runtimePlatform.cpuArchitecture in the task definition. Running a plain docker build on an Apple Silicon laptop gives an arm64 image; if the task definition says X86_64, the task fails to start, often with nothing more than exec format error. The same applies the other way round. So always state --platform when building, and maintain it in the same place as the task definition.

The shop picks ARM64: for the same vCPU and memory, Graviton Fargate costs less than x86_64, and cross-compiling Go needs no emulator. --platform=$BUILDPLATFORM runs the compiler on the build machine’s native architecture, and the second stage only copies a file, with no RUN at all, so building arm64 images on an x86 CI machine is fast too. Stay on X86_64 only when the program depends on cgo or on libraries that exist only for x86.

Step 5: Write the task definition

First the complete task definition for order, then section by section:

{
	"family": "shop-order",
	"requiresCompatibilities": ["FARGATE"],
	"networkMode": "awsvpc",
	"cpu": "512",
	"memory": "1024",
	"runtimePlatform": {
		"cpuArchitecture": "ARM64",
		"operatingSystemFamily": "LINUX"
	},
	"executionRoleArn": "arn:aws:iam::111122223333:role/shop-ecs-execution",
	"taskRoleArn": "arn:aws:iam::111122223333:role/shop-order-task",
	"containerDefinitions": [
		{
			"name": "order",
			"image": "111122223333.dkr.ecr.ap-northeast-1.amazonaws.com/shop/order:3f2c1a9e4b7d",
			"essential": true,
			"portMappings": [
				{ "name": "http", "containerPort": 8080, "protocol": "tcp", "appProtocol": "http" }
			],
			"environment": [
				{
					"name": "DB_HOST",
					"value": "shop-prod-order.abcdefghijkl.ap-northeast-1.rds.amazonaws.com"
				},
				{ "name": "DB_NAME", "value": "order" },
				{ "name": "NATS_URL", "value": "nats://nats.shop.internal:4222" }
			],
			"secrets": [
				{
					"name": "DB_PASSWORD",
					"valueFrom": "arn:aws:secretsmanager:ap-northeast-1:111122223333:secret:shop/prod/order-AbCdEf:password::"
				}
			],
			"logConfiguration": {
				"logDriver": "awslogs",
				"options": {
					"awslogs-group": "/ecs/shop/order",
					"awslogs-region": "ap-northeast-1",
					"awslogs-stream-prefix": "order",
					"mode": "non-blocking",
					"max-buffer-size": "25m"
				}
			},
			"healthCheck": {
				"command": ["CMD", "/app/server", "healthcheck"],
				"interval": 15,
				"timeout": 5,
				"retries": 3,
				"startPeriod": 20
			},
			"stopTimeout": 30,
			"readonlyRootFilesystem": true
		}
	]
}

CPU and memory come only in fixed combinations. Fargate bills per task; cpu is in CPU units (1024 is 1 vCPU) and memory in MiB, and the pair must be one of the combinations below, or registration is rejected:

cpuAllowed memory
256 (0.25)512, 1024, 2048
512 (0.5)1024 to 4096, in steps of 1024
1024 (1)2048 to 8192, in steps of 1024
2048 (2)4096 to 16384, in steps of 1024
4096 (4)8192 to 30720, in steps of 1024
8192 (8) and upWider ranges, coarser steps; see the AWS documentation

How to choose? Measure one task’s peak CPU and memory under a load test, then add headroom. Go services usually use more CPU than memory; when memory is set tight, also set GOMEMLIMIT slightly below the task’s memory so the garbage collector works earlier instead of the task being OOM-killed (see “CPU and Memory Problems in Production Go Services: How to Track Them Down”).

networkMode: awsvpc: the only mode Fargate supports. Each task has its own network interface, private IP and security group, which is why the ALB target group uses the ip target type.

The name in portMappings: Service Connect in step 9 refers to the port by this name, so name it now.

Keep environment and secrets apart. Ordinary settings go in environment, which appears in the task definition for anyone who can read it; passwords and keys always go in secrets, where the task definition holds only a reference. valueFrom can point at Secrets Manager or at SSM Parameter Store; for Secrets Manager you can append :json-key:version-stage:version-id to the ARN to take one field of a JSON secret (the :password:: above; the last two parts left empty mean the current version).

Secrets Manager shop/prod/order ① Pull image from ECR ② Read secrets execution role ③ Set env vars DB_PASSWORD ④ Start program /app/server serve After a secret rotation RDS rotates password new value in the store Running tasks keep the old value Redeploy new tasks get it

Figure: when a task starts, Fargate reads Secrets Manager with the task execution role, hands the values to the container as environment variables, and only then starts the program. If the secret is rotated later, running tasks keep the old value until the next deployment.

That last point matters: secrets are read once, when the task starts. After RDS rotates a password automatically, running tasks do not find out; either force a redeployment after rotation (aws ecs update-service --force-new-deployment), or have the program read the secret itself with the SDK and refresh it periodically. The shop does the former, with the rotation schedule and the deployment steps written in the same runbook.

SSM Parameter Store or Secrets Manager? Standard Parameter Store parameters cost nothing extra and suit ordinary settings and values that never rotate; Secrets Manager charges per secret and per API call but has rotation built in (RDS can manage the master password directly). Database passwords and payment-provider keys go in Secrets Manager; feature switches and external URLs go in Parameter Store or straight into environment.

logConfiguration: the awslogs driver sends the container’s standard output to CloudWatch Logs; the log group /ecs/shop/order must exist beforehand, with a retention period set. mode decides what happens when CloudWatch temporarily cannot accept writes: blocking makes the program stall while writing logs; non-blocking buffers up to max-buffer-size and drops what does not fit. ECS changed the default to non-blocking in June 2025; the shop writes it out so readers of the config do not need to know that history.

healthCheck: this is the container health check. ECS runs the command inside the container; after retries failures the task is marked unhealthy and the service replaces it. There is a trap here: a distroless image has no shell and no curl. AWS documentation examples often use ["CMD-SHELL", "curl -f http://localhost/ || exit 1"], which in distroless always fails because /bin/sh does not exist, and the service keeps replacing tasks that are perfectly fine. The right way is the CMD form, running the program’s own healthcheck subcommand directly (the code in step 6).

stopTimeout: how long to wait after SIGTERM before sending SIGKILL. The default is 30 seconds and Fargate’s maximum is 120. Step 6 explains how it works together with the ALB.

readonlyRootFilesystem: Go services rarely write local files; a read-only root blocks a whole class of attacks. When temporary files really are needed, mount a volume.

Step 6: Create the service behind the ALB

First, the sections you fill in when creating a service in the console; each maps to a concept from earlier:

Schematic: create service (not the real console) 1 Cluster, task def Cluster shop-prod Task definition shop-api-gateway:42 2 Compute Capacity FARGATE Platform LATEST 3 Networking Subnets private × 3 Security group sg-gw Public IP off 4 Load balancing ALB shop-prod Target group /readyz Container port 8080 5 Deployment Rolling 100% / 200% Circuit breaker on + rollback 6 Autoscaling Tasks 3 to 20 Target 400 req per task

Figure (schematic, not the real console): ① cluster and task definition ② compute: Fargate ③ networking: private subnets, the task security group, no public IP ④ load balancing: ALB, target group and health check ⑤ deployment: rolling update and circuit breaker ⑥ autoscaling.

The console is good for a first exploration; production has to be reproducible, so the shop uses CLI JSON (or the Terraform in step 10). The target group first:

aws elbv2 create-target-group --name shop-api-gateway \
  --protocol HTTP --port 8080 --target-type ip \
  --vpc-id vpc-0shop0prod \
  --health-check-path /readyz --matcher HttpCode=200 \
  --health-check-interval-seconds 10 --health-check-timeout-seconds 5 \
  --healthy-threshold-count 2 --unhealthy-threshold-count 2

aws elbv2 modify-target-group-attributes \
  --target-group-arn "$TG_ARN" \
  --attributes Key=deregistration_delay.timeout_seconds,Value=30

Then the api-gateway service:

{
	"cluster": "shop-prod",
	"serviceName": "api-gateway",
	"taskDefinition": "shop-api-gateway",
	"desiredCount": 3,
	"launchType": "FARGATE",
	"networkConfiguration": {
		"awsvpcConfiguration": {
			"subnets": ["subnet-0a1private1a", "subnet-0b2private1c", "subnet-0c3private1d"],
			"securityGroups": ["sg-0api0gateway0task"],
			"assignPublicIp": "DISABLED"
		}
	},
	"loadBalancers": [
		{
			"targetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:111122223333:targetgroup/shop-api-gateway/943f017f100becff",
			"containerName": "api-gateway",
			"containerPort": 8080
		}
	],
	"healthCheckGracePeriodSeconds": 30,
	"deploymentConfiguration": {
		"strategy": "ROLLING",
		"minimumHealthyPercent": 100,
		"maximumPercent": 200,
		"deploymentCircuitBreaker": { "enable": true, "rollback": true },
		"alarms": { "alarmNames": ["shop-api-gateway-5xx"], "enable": true, "rollback": true }
	},
	"serviceConnectConfiguration": { "enabled": true, "namespace": "shop.local" },
	"availabilityZoneRebalancing": "ENABLED",
	"enableECSManagedTags": true,
	"propagateTags": "SERVICE"
}
aws ecs create-service --cli-input-json file://api-gateway-service.json

Why these fields:

  • Three private subnets, three tasks. ECS spreads tasks across Availability Zones by default; availabilityZoneRebalancing spreads them evenly again once a zone recovers.
  • assignPublicIp: DISABLED. Tasks live in private subnets and go out through NAT or VPC endpoints. A public IP is only needed when running Fargate in “public subnets without NAT”, which exposes every task to the internet and is not recommended.
  • The two health checks do different jobs. The ALB health check calls /readyz and decides “should requests go to this task”; the container health check calls /livez and decides “is this process stuck and in need of replacing”. Keeping them apart means that when the database is briefly unreachable, /readyz fails and the ALB pauses traffic, but all tasks are not killed and restarted at once.
  • healthCheckGracePeriodSeconds. For this long after a task starts, ECS ignores health-check failures. Set it to “the time from start until /readyz returns 200” plus a little; too short, and a slow-starting version is treated as broken and restarted over and over.

The stop sequence: deregister first, then SIGTERM

When a task is stopped (replaced during a deployment, scaled in, failed health checks), ECS always follows the same order:

ALB Container traffic draining: in-flight requests only out of the target group running, finishing requests shutting down exited stop requested SIGTERM SIGKILL if not exited deregistration_delay ≤ 30 s Go budget 20 s stopTimeout 30 s

Figure: the task first enters draining in the target group; the ALB stops sending new requests, and in-flight requests get at most deregistration_delay; then ECS sends SIGTERM, and the program must exit on its own within stopTimeout, or it is SIGKILLed.

  1. Deregistration (DEACTIVATING). ECS deregisters the task from the target group. The ALB sends it no new requests, and requests already in progress get at most deregistration_delay (300 seconds by default).
  2. SIGTERM (STOPPING). When deregistration completes, ECS sends SIGTERM to the container.
  3. SIGKILL. If the program has not exited after stopTimeout, it is killed.

So the two numbers fit together like this:

  • deregistration_delay should be a little longer than the longest normal request, and no more. The shop’s slowest call is payment calling the payment provider, with a 10-second timeout, so it uses 30 seconds. With the default 300 seconds, every old task waits five idle minutes on every deployment.
  • The Go program’s shutdown budget after SIGTERM (20 seconds below) must be shorter than stopTimeout (30 seconds), or SIGKILL arrives first, halfway through a transaction.

Compared with the Kubernetes approach in “Configuration and Graceful Shutdown in Go”, ECS already deregisters before sending SIGTERM, so the program does not need to “fail readiness first and sleep a few seconds”; it should still make /readyz fail and shut down gracefully, because tasks can be stopped for other reasons too. Here is the service skeleton in cmd/order/main.go:

package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"net"
	"net/http"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
	"time"
)

var version = "dev" // set at build time with -ldflags "-X main.version=<git SHA>"

func main() {
	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil))) // one JSON object per line, queryable in CloudWatch Logs
	cmd := "serve"
	if len(os.Args) > 1 {
		cmd = os.Args[1]
	}
	switch cmd {
	case "healthcheck": // for the ECS container health check: distroless has no curl
		os.Exit(healthcheck("http://127.0.0.1:8080/livez"))
	case "serve":
		ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
		defer stop()
		ln, err := net.Listen("tcp", ":8080")
		if err != nil {
			slog.Error("listen", "err", err)
			os.Exit(1)
		}
		app := http.NewServeMux()
		app.HandleFunc("POST /orders", func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(http.StatusCreated) // real order creation omitted
		})
		if err := run(ctx, ln, app, 20*time.Second); err != nil {
			slog.Error("serve", "err", err)
			os.Exit(1)
		}
	default:
		fmt.Fprintln(os.Stderr, "unknown command:", cmd)
		os.Exit(2)
	}
}

// run serves /livez, /readyz and the app routes; once ctx ends (SIGTERM) it shuts down within grace.
func run(ctx context.Context, ln net.Listener, app http.Handler, grace time.Duration) error {
	var ready atomic.Bool
	mux := http.NewServeMux()
	mux.HandleFunc("GET /livez", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK) // alive if the process can answer; no database check
	})
	mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
		if !ready.Load() {
			http.Error(w, "draining", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK) // a real service checks its connection pool here
	})
	mux.Handle("/", app)

	srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	errc := make(chan error, 1)
	go func() { errc <- srv.Serve(ln) }()
	ready.Store(true)
	slog.Info("started", "addr", ln.Addr().String(), "version", version)

	select {
	case err := <-errc:
		return err // stopped before any signal: always an error
	case <-ctx.Done():
	}
	slog.Info("SIGTERM received, draining")
	ready.Store(false)

	// grace must be shorter than stopTimeout in the task definition, or SIGKILL arrives first.
	sctx, cancel := context.WithTimeout(context.Background(), grace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return fmt.Errorf("shutdown: %w", err)
	}
	if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	// only now close the database pool and flush remaining traces (omitted).
	slog.Info("bye")
	return nil
}

// healthcheck returns a process exit code: 0 means healthy.
func healthcheck(url string) int {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return 1
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return 1 // ECS only looks at the exit code; write nothing to stderr
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 1
	}
	return 0
}

run takes a net.Listener that is already open, so a test can listen on 127.0.0.1:0 on a random port, send a request that takes 300 milliseconds, cancel the context, and check that the request still gets 201, that run returns cleanly, and that the health check then returns 1. Locally, docker stop (which also sends SIGTERM) shows the same log sequence: started, SIGTERM received, draining, bye, exit code 0.

Step 7: Deployment and rollback: rolling updates, the circuit breaker, blue-green and canary

ECS’s default deployment is a rolling update: minimumHealthyPercent and maximumPercent decide how many extra new tasks may start at once and how many healthy tasks must remain.

Before :41 :41 :41 During (up to 200%) :41 :41 :41 :42 :42 :42 Done :42 :42 :42 When the new version cannot start New tasks fail to start or fail health checks Failures hit threshold circuit breaker trips Rolled back to :41 CI shows failure

Figure: with 3 desired tasks, a 100% minimum and a 200% maximum, ECS first starts 3 tasks of the new version and stops the old ones only after the new ones pass health checks; if the new version keeps failing to start, the circuit breaker returns the service to the last task definition that worked.

Setting (3 desired)Behaviour during a deploymentFits
100% / 200%Start up to 3 extra new tasks; stop old ones once they are healthyProduction: capacity never drops below 3; briefly paying double
50% / 100%Stop 1 old task, start 1 new one, and repeatDevelopment, or plenty of spare capacity: no extra cost, but capacity dips
100% / 150%Start 1 extra new task at a timeMany tasks, when peak cost during deployments matters

The deployment circuit breaker handles “the new version cannot even start”: tasks keep failing to start or keep failing health checks, and once failures reach a threshold (calculated from the desired count), ECS declares the deployment failed; with rollback on, it automatically switches back to the last task definition that worked. Without the circuit breaker, the service retries for ever, and CI’s “wait for the service to be stable” waits until it times out.

Alarm-based rollback (alarms) handles “the new version starts but behaves wrongly”: if a named CloudWatch alarm (such as the ALB’s 5xx count) goes into alarm during the deployment, ECS rolls back as well. The circuit breaker watches whether tasks can live; the alarm watches whether users are affected. Turn on both.

Manual rollback means pointing the service back at an old revision:

aws ecs update-service --cluster shop-prod --service api-gateway \
  --task-definition shop-api-gateway:41
aws ecs wait services-stable --cluster shop-prod --services api-gateway

That is exactly why task definitions keep every revision and why ECR tags are immutable: the image behind :41 is always the one it was then. Only the code is rolled back; database changes need separate thought, see the expand-and-contract approach in “Blue-Green and Canary Releases: Doing Them Right and What to Watch For”.

Blue-green and canary. A rolling update cannot control “what share of users get the new version first”. ECS now has three advanced strategies built in, all switching weighted traffic between two ALB target groups: BLUE_GREEN (switch everything once the new version is ready, keeping a bakeTimeInMinutes observation window during which you can switch back within seconds), CANARY (shift a small share first, the rest after observing) and LINEAR (shift equal steps each time). They need an advancedConfiguration in loadBalancers (the second target group, the production listener rule, and a role that lets ECS modify the ALB), and lifecycle hooks can call Lambda for custom checks. The older route was to let CodeDeploy drive it; new services need not take that path. Which changes deserve a canary, how to set the percentages and which metrics to watch were covered in the previous article, and the ideas are exactly the same; the shop uses CANARY for payment and keeps the other services on rolling updates with alarm-based rollback.

Step 8: Autoscaling: on CPU or on requests per task

The number of replicas of an ECS service is adjusted by Application Auto Scaling. The most common policy is target tracking: you give a target value and it works out how many tasks are needed.

aws application-autoscaling register-scalable-target \
  --service-namespace ecs --scalable-dimension ecs:service:DesiredCount \
  --resource-id service/shop-prod/api-gateway \
  --min-capacity 3 --max-capacity 20

aws application-autoscaling put-scaling-policy \
  --service-namespace ecs --scalable-dimension ecs:service:DesiredCount \
  --resource-id service/shop-prod/api-gateway \
  --policy-name requests-per-task --policy-type TargetTrackingScaling \
  --target-tracking-scaling-policy-configuration file://requests-per-task.json
{
	"TargetValue": 400.0,
	"PredefinedMetricSpecification": {
		"PredefinedMetricType": "ALBRequestCountPerTarget",
		"ResourceLabel": "app/shop-prod/50dc6c495c0c9188/targetgroup/shop-api-gateway/943f017f100becff"
	},
	"ScaleOutCooldown": 60,
	"ScaleInCooldown": 300
}
MetricFitsWhyDoesn’t fit
ECSServiceAverageCPUUtilizationMost synchronous APIs (order, payment)Load on a Go service usually shows up first in CPUServices that mostly wait on external APIs: low CPU but already saturated
ALBRequestCountPerTargetapi-gateway, which sits directly behind the ALBRequests react earlier than CPU; the target converts directly from a load testServices not behind the ALB; services whose per-request cost varies a lot
ECSServiceAverageMemoryUtilizationRarely used on its ownGo does not give memory back as soon as load drops, so scaling in is sluggishOrdinary Go services

ResourceLabel is built from the latter parts of the ALB and target group ARNs. A target of 400 means “400 requests per task per minute on average”, taken from a load test: a single task handles about 600 while latency is still acceptable, leaving a third as headroom.

Some practical points:

  • Scaling out takes time. Fargate pulls the image afresh every time a task starts, then the health checks have to pass; it usually takes a minute or two. Smaller images start faster, which is a concrete benefit of distroless and -ldflags="-s -w".
  • Scale ahead of known peaks. For the Friday 20:00 sale, a scheduled action raises the minimum at 19:30 instead of waiting for the metric to catch up: aws application-autoscaling put-scheduled-action with --schedule "cron(30 19 ? * FRI *)" and --timezone Asia/Taipei, and another scheduled action to lower it afterwards.
  • The replica cap must fit the database’s connections. max-capacity × per-task pool limit has to fit within PostgreSQL’s max_connections, for the same reason as on EKS.
  • Fargate Spot. Interruptible work (such as background batches) can use the FARGATE_SPOT capacity provider at a much lower price, but AWS gives only two minutes’ notice before reclaiming the capacity. Synchronous services like payment stay on regular Fargate, or at least use the capacity provider strategy’s base to keep a fixed number of regular tasks.

Step 9: How services call each other

api-gateway calls order and payment. In Compose the service name was enough; on ECS every task’s IP changes, so service discovery is needed. Three approaches:

api-gateway task api-gateway program calls http://order:8080 Service Connect proxy added by ECS order task 1 proxy order program order task 2 proxy order program to healthy tasks namespace shop.local Cloud Map register and look up

Figure: api-gateway calls http://order:8080; the Service Connect proxy that ECS adds to the task uses the registrations in the shop.local namespace to spread the requests over healthy order tasks, and records metrics for every call.

ApproachHow it worksFitsCost or limits
Service ConnectECS adds a proxy container to each task; names are registered in Cloud MapServices that all run on ECS calling each other (the shop’s choice)The proxy uses part of the task’s CPU and memory; callers must enable it too and be redeployed
Cloud Map DNS (service discovery)Each task’s IP is registered as a DNS recordCallers outside ECS (for example a legacy system on EC2)Depends on DNS caching and TTLs; no load balancing, retries or metrics
Internal ALBA non-public ALB in front of each serviceWhen ALB routing rules are needed, or calls cross VPCsOne more hop and one more ALB to pay for

Service Connect is configured on both sides. order, which serves requests, declares its name and port (portName matches the name in the task definition’s portMappings):

{
	"cluster": "shop-prod",
	"serviceName": "order",
	"taskDefinition": "shop-order",
	"desiredCount": 2,
	"launchType": "FARGATE",
	"networkConfiguration": {
		"awsvpcConfiguration": {
			"subnets": ["subnet-0a1private1a", "subnet-0b2private1c", "subnet-0c3private1d"],
			"securityGroups": ["sg-0order0task"],
			"assignPublicIp": "DISABLED"
		}
	},
	"serviceConnectConfiguration": {
		"enabled": true,
		"namespace": "shop.local",
		"services": [
			{
				"portName": "http",
				"discoveryName": "order",
				"clientAliases": [{ "port": 8080, "dnsName": "order" }]
			}
		]
	},
	"deploymentConfiguration": {
		"deploymentCircuitBreaker": { "enable": true, "rollback": true }
	}
}

api-gateway, which only calls others, needs just "serviceConnectConfiguration": { "enabled": true, "namespace": "shop.local" } (already in the service definition in step 6). The URL in the code is http://order:8080, the same as under Compose, so the configuration does not change. Note that order is not behind the ALB, so it has only the container health check; order’s security group must allow 8080 from api-gateway’s security group.

Service Connect handles “who to find and how to spread the load”; timeout and retry policies still live in the code, see “Timeouts, Retries and Circuit Breakers”.

What about events? order.placed goes through NATS JetStream. A message broker is a stateful component that needs stable disks and a fixed identity, which does not suit Fargate tasks that can be replaced at any moment. The shop runs its NATS cluster on three fixed EC2 instances (one per Availability Zone), and tasks connect through NATS_URL; with Kafka instead, Amazon MSK lets AWS manage the brokers and storage.

Step 10: The delivery flow: Terraform for the foundations, GitHub Actions for versions

By now everything can be created with the CLI, but production has to be reproducible and reviewable. The shop splits the work two ways:

  • Terraform manages what “rarely changes”: the VPC, subnets, NAT, endpoints, the ALB, target groups, security groups, IAM roles, the ECS cluster and the services themselves, and autoscaling.
  • CI manages what “changes on every commit”: images and new task definition revisions.

The boundary must be explicit, or the two overwrite each other. The classic conflict: CI deploys shop-api-gateway:42, the next person runs terraform apply, Terraform sees the service pointing at a version it does not remember, and changes the service back: a silent rollback. The fix is to have Terraform ignore those fields:

# infra/prod/ecs-api-gateway.tf (excerpt: target group, service, autoscaling)
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "vpc_id" { type = string }
variable "private_subnet_ids" { type = list(string) }
variable "task_security_group_id" { type = string }
variable "https_listener_arn" { type = string }
variable "cluster_arn" { type = string }

resource "aws_lb_target_group" "api_gateway" {
  name                 = "shop-api-gateway"
  port                 = 8080
  protocol             = "HTTP"
  target_type          = "ip" # Fargate tasks use awsvpc; targets are task IPs
  vpc_id               = var.vpc_id
  deregistration_delay = 30 # default 300 s; longer than the longest request, but no more

  health_check {
    path                = "/readyz"
    matcher             = "200"
    interval            = 10
    timeout             = 5
    healthy_threshold   = 2
    unhealthy_threshold = 2
  }
}

resource "aws_lb_listener_rule" "api_gateway" {
  listener_arn = var.https_listener_arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.api_gateway.arn
  }
  condition {
    path_pattern { values = ["/api/*"] }
  }
}

resource "aws_ecs_service" "api_gateway" {
  name                              = "api-gateway"
  cluster                           = var.cluster_arn
  task_definition                   = "shop-api-gateway" # used on first creation; CI updates it afterwards
  desired_count                     = 3
  launch_type                       = "FARGATE"
  health_check_grace_period_seconds = 30

  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200
  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  network_configuration {
    subnets          = var.private_subnet_ids
    security_groups  = [var.task_security_group_id]
    assign_public_ip = false
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.api_gateway.arn
    container_name   = "api-gateway"
    container_port   = 8080
  }

  lifecycle {
    # CI changes the version, autoscaling the count; Terraform must not revert them
    ignore_changes = [task_definition, desired_count]
  }
}

resource "aws_appautoscaling_target" "api_gateway" {
  service_namespace  = "ecs"
  scalable_dimension = "ecs:service:DesiredCount"
  resource_id        = "service/shop-prod/${aws_ecs_service.api_gateway.name}"
  min_capacity       = 3
  max_capacity       = 20
}

resource "aws_appautoscaling_policy" "api_gateway_cpu" {
  name               = "cpu-60"
  policy_type        = "TargetTrackingScaling"
  service_namespace  = aws_appautoscaling_target.api_gateway.service_namespace
  scalable_dimension = aws_appautoscaling_target.api_gateway.scalable_dimension
  resource_id        = aws_appautoscaling_target.api_gateway.resource_id

  target_tracking_scaling_policy_configuration {
    target_value       = 60
    scale_out_cooldown = 60
    scale_in_cooldown  = 300
    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageCPUUtilization"
    }
  }
}

desired_count is ignored for the same reason: after autoscaling has raised the count to 12, a terraform apply should not knock it back to 3. The VPC, NAT and endpoints are built with the community terraform-aws-modules/vpc/aws module, the same shape as the EKS VPC in the next article, so they are not repeated here.

GitHub Actions: deploying over OIDC, with no long-lived keys

① Push to main triggers the workflow ② OIDC to credentials configure-aws-credentials ③ Build and push arm64 image to ECR ④ Fill in the image render-task-definition ⑤ Register, update deploy-task-definition ⑥ Wait until stable wait-for-service-stability Success: the new revision is live Failure: the circuit breaker rolls back and CI turns red

Figure: ① push to main ② exchange OIDC for temporary AWS credentials ③ build the arm64 image and push it to ECR ④ put the new image into the task definition ⑤ register a new revision and update the service ⑥ wait until the service is stable; on failure, the circuit breaker rolls back.

Four official AWS actions map onto these steps:

# .github/workflows/deploy.yaml
name: deploy
on:
  push:
    branches: [main]
permissions:
  id-token: write # ask GitHub for an OIDC token
  contents: read
concurrency: deploy-prod # one deployment at a time; later runs queue
jobs:
  deploy:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service: [api-gateway, order, payment]
    env:
      AWS_REGION: ap-northeast-1
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/shop-ci-deploy
          aws-region: ${{ env.AWS_REGION }}
      - id: ecr
        uses: aws-actions/amazon-ecr-login@v2
      - uses: docker/setup-buildx-action@v4
      - id: build
        env:
          IMAGE: ${{ steps.ecr.outputs.registry }}/shop/${{ matrix.service }}:${{ github.sha }}
        run: |
          docker buildx build --platform linux/arm64 \
            --build-arg SERVICE=${{ matrix.service }} --build-arg VERSION=${{ github.sha }} \
            -f deploy/docker/Dockerfile -t "$IMAGE" --push .
          echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: deploy/ecs/${{ matrix.service }}-taskdef.json
          container-name: ${{ matrix.service }}
          image: ${{ steps.build.outputs.image }}
      - uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: shop-prod
          service: ${{ matrix.service }}
          wait-for-service-stability: true
  • The task definition lives in the repository (deploy/ecs/order-taskdef.json), and the render step swaps in the image that was just pushed. Changes to the task definition therefore go through PR review too.
  • wait-for-service-stability makes CI succeed only once the service is stable; if the circuit breaker rolls back, this step fails, and the team sees red in CI instead of believing the deployment worked.
  • Pin third-party actions to a commit SHA in production rather than a major-version tag; see “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain” for why.

The CI role’s trust policy only allows the main branch of example/shop to assume it (written the same way as the CI role for EKS in the next article, with the sub condition limiting repository and branch). Its permissions cover only what a deployment needs:

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "EcrLogin",
			"Effect": "Allow",
			"Action": "ecr:GetAuthorizationToken",
			"Resource": "*"
		},
		{
			"Sid": "EcrPush",
			"Effect": "Allow",
			"Action": [
				"ecr:BatchCheckLayerAvailability",
				"ecr:BatchGetImage",
				"ecr:InitiateLayerUpload",
				"ecr:UploadLayerPart",
				"ecr:CompleteLayerUpload",
				"ecr:PutImage"
			],
			"Resource": "arn:aws:ecr:ap-northeast-1:111122223333:repository/shop/*"
		},
		{
			"Sid": "RegisterTaskDefinition",
			"Effect": "Allow",
			"Action": ["ecs:RegisterTaskDefinition", "ecs:DescribeTaskDefinition"],
			"Resource": "*"
		},
		{
			"Sid": "UpdateShopServices",
			"Effect": "Allow",
			"Action": ["ecs:UpdateService", "ecs:DescribeServices"],
			"Resource": "arn:aws:ecs:ap-northeast-1:111122223333:service/shop-prod/*"
		},
		{
			"Sid": "PassOnlyTaskRoles",
			"Effect": "Allow",
			"Action": "iam:PassRole",
			"Resource": [
				"arn:aws:iam::111122223333:role/shop-ecs-execution",
				"arn:aws:iam::111122223333:role/shop-*-task"
			],
			"Condition": { "StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" } }
		}
	]
}

The one most often overlooked is iam:PassRole. Registering a task definition amounts to saying “let ECS use these two roles”, so CI needs permission to hand roles to ECS. Written as "Resource": "*", anyone who can change a task definition could make a task assume the most powerful role in the account. Limit the role names, and use iam:PassedToService so they can only be handed to ECS tasks; even if the CI role leaks, what it can do is limited.

Step 11: Logs, metrics and cost

Logs. One log group per service, with a retention period (the default keeps logs for ever, and the cost keeps accumulating):

aws logs create-log-group --log-group-name /ecs/shop/order
aws logs put-retention-policy --log-group-name /ecs/shop/order --retention-in-days 30
aws logs tail /ecs/shop/order --follow --since 10m --filter-pattern '"SIGTERM"'

The program writes one JSON object per line (slog.NewJSONHandler), so CloudWatch Logs Insights can query by field. How to put trace IDs and request IDs into logs is covered in “Observability in Go: Logs, Metrics and Tracing”.

Metrics. Start with these; most investigations begin here:

SourceMetricWhat it tells you
ALBHTTPCode_Target_5XX_Count, TargetResponseTimeWhether users are affected; the deployment rollback alarm uses this
ALB target groupUnHealthyHostCount, RequestCountPerTargetWhether tasks are failing health checks; whether scaling keeps up
ECS serviceCPUUtilization, MemoryUtilizationWhether the task size is right; the basis for autoscaling
ECS eventsService events, stoppedReason of stopped tasksWhy tasks were replaced: failed health checks, OOM, image pull failures
Container InsightsPer-task CPU, memory, networkPer-task detail, visible only once enabled on the cluster

When tasks keep restarting, look first at the stoppedReason of the stopped tasks: CannotPullContainerError is usually networking (no NAT or endpoints) or the execution role’s permissions; ResourceInitializationError is often a secret that cannot be read; Essential container in task exited means reading the logs to see why the program quit; OutOfMemoryError means the memory setting is too small.

Cost. Fargate’s pricing is simple, but a few items are easy to miss:

  • Fargate itself is billed per second (with a minimum) by the vCPU and memory the task declares. ARM64 is cheaper than x86_64; steady usage can use Compute Savings Plans. Waste usually comes from “oversized tasks”; check real usage in Container Insights and adjust.
  • NAT gateways charge per hour plus per GB processed. One NAT per Availability Zone, multiplied by traffic, is often the second-largest line on the bill; the VPC endpoints in step 2 exist for this.
  • The ALB charges per hour plus usage units (LCUs). One ALB per service adds up quickly; the shop has a single public ALB with path rules, and internal calls go through Service Connect.
  • Public IPv4 addresses are charged per hour. Not giving tasks public IPs saves this as well as being safer.
  • CloudWatch Logs charges by ingestion and storage; do not leave debug-level logging on in production.
  • Traffic between Availability Zones is charged too. Service-to-service calls inevitably cross zones; usually small, but watch services that move a lot of data.

Actual prices vary by Region and over time; the AWS pricing pages are the reference. Once everything is built, enable cost allocation tags (propagateTags: SERVICE makes tasks carry the service’s tags) and break the bill down by service.

Common pitfalls

  • The image architecture does not match runtimePlatform. An arm64 image built on Apple Silicon with X86_64 in the task definition exits immediately, with only exec format error in the logs. Always pass --platform when building.
  • Using CMD-SHELL for the health check in a distroless image. There is no /bin/sh, so the health check always fails and the service keeps replacing healthy tasks. Use ["CMD", "/app/server", "healthcheck"].
  • Private subnets with neither NAT nor endpoints. Tasks cannot pull images, and the stop reason is CannotPullContainerError. You need at least one of the two; with ECR endpoints but no S3 gateway endpoint, image layers still cannot be pulled.
  • Putting secrets in environment. Anyone who can read the task definition sees them, and they stay in every revision. Always use secrets.
  • Assuming secret rotation takes effect by itself. Secrets are read only when a task starts; redeploy after rotating.
  • Mixing up the task execution role and the task role. Put S3 read permission on the execution role and the program cannot use it at run time; put secret read permission on the task role and the task cannot read its secrets at start-up.
  • Leaving deregistration_delay at the default 300 seconds. Every old task idles for five minutes on every deployment; deployments become slow and look stuck.
  • A shutdown budget longer than stopTimeout. SIGKILL arrives first, halfway through a transaction; Fargate’s stopTimeout is at most 120 seconds.
  • healthCheckGracePeriodSeconds too short. A slower-starting version is judged unhealthy while warming up, the deployment never completes, and finally the circuit breaker trips.
  • No deployment circuit breaker. When the new version cannot start, the service retries for ever and CI only fails at its timeout.
  • Terraform not ignoring task_definition and desired_count. The next terraform apply silently reverts the service to an old version and knocks the replica count back to the minimum.
  • iam:PassRole on *. Anyone who can change a task definition can make a task assume any role.
  • A task security group allowing 0.0.0.0/0. Anything in the same VPC can bypass the ALB and connect directly; the source should be the ALB’s security group.
  • Log groups without retention. The default keeps logs for ever and the cost grows every month.
  • Running a message broker or database in Fargate tasks. Tasks can be replaced at any time and their local disk disappears; stateful components belong on RDS, MSK or fixed EC2 instances.

Key takeaways

  • Start with how much you manage: EC2 down to the operating system, Elastic Beanstalk for a single application, ECS Fargate only containers, EKS a cluster, Lambda only functions, and static front ends on S3 plus CloudFront. App Runner no longer accepts new customers; ECS Express Mode gives a similar experience.
  • A few containerised long-running services, a small team, no wish to operate Kubernetes: ECS Fargate is the most direct choice; move to EKS when the Kubernetes ecosystem is needed.
  • Networking: the VPC spans two or three Availability Zones; public subnets hold only the ALB and NAT, tasks sit in private subnets without public IPs, databases in database subnets; security groups are chained with “the source is the previous layer’s security group”.
  • NAT gateways charge by data volume; ECR, S3, CloudWatch Logs and Secrets Manager can go through VPC endpoints, and the S3 gateway endpoint costs nothing extra.
  • ECS’s four nouns: a task definition is a versioned blueprint, a service keeps the task count and connects to the ALB, a task is a replica, a cluster is a grouping. The execution role is for ECS to start tasks, the task role is for the program, one per service.
  • Task definitions: fixed CPU and memory combinations; runtimePlatform matching the image’s architecture; secrets in secrets, read only at start-up; health checks in CMD form calling the program’s own subcommand.
  • The stop sequence is deregister from the target group, then SIGTERM, then SIGKILL after stopTimeout; deregistration_delay slightly longer than the longest request, the Go shutdown budget shorter than stopTimeout.
  • Deployment: in production, rolling updates at 100% / 200% with the circuit breaker and alarm-based rollback on; when percentages need control, use ECS’s built-in blue-green, canary or linear strategies.
  • Autoscale with target tracking: requests per task for services behind the ALB, CPU for the rest; scale ahead of known peaks with schedules; the replica cap must fit the database’s connections.
  • Terraform for the foundations, CI for versions, with Terraform ignoring task_definition and desired_count; CI exchanges OIDC for temporary credentials, and iam:PassRole is limited by role and service.

References

Next

By now the shop’s three services run on Fargate across Availability Zones, deployments have a circuit breaker and rollback, replicas are added automatically when traffic rises, and the team manages no machines at all. This setup will last a long time; but once there are more services, Operators are needed, scaling has to follow queue backlogs, or the same deployment method has to work across clouds, Kubernetes itself is needed. The next article, “Deploying on AWS: EKS and Elastic Scaling”, puts the same shop on EKS and shows how clusters, nodes and pods scale with load; for the same “no machines to manage” approach on another cloud, the later “Deploying on GCP: Running Container Services on Cloud Run” covers Cloud Run.