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.
In this article
- What this article solves
- Step 1: Choose a path: six ways to run services on AWS
- Step 2: The networking building blocks: VPCs, subnets, NAT and security groups
- Step 3: ECS itself: clusters, services, tasks and task definitions
- Step 4: Push images to ECR
- Step 5: Write the task definition
- Step 6: Create the service behind the ALB
- Step 7: Deployment and rollback: rolling updates, the circuit breaker, blue-green and canary
- Step 8: Autoscaling: on CPU or on requests per task
- Step 9: How services call each other
- Step 10: The delivery flow: Terraform for the foundations, GitHub Actions for versions
- Step 11: Logs, metrics and cost
- Common pitfalls
- Key takeaways
- References
- 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
.envfile on the machine, and people who have since left have seen it. - For the Friday-night flash sale,
api-gatewaygets 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:
- Choosing a path: what EC2, Elastic Beanstalk, ECS Fargate, EKS, Lambda and S3 plus CloudFront each fit, and why the shop picks ECS Fargate.
- The networking building blocks: Regions and Availability Zones, VPCs, public and private subnets, NAT gateways and VPC endpoints, security groups, the ALB.
- ECS itself: clusters, services, tasks and task definitions, plus two IAM roles that are easy to confuse.
- Pushing images to ECR, with a CPU architecture that matches the task definition.
- Writing the task definition: CPU and memory, ports, logs, secrets, health checks.
- Creating the service behind the ALB: health checks, the stop sequence, and what the Go side has to do.
- Deployment and rollback: rolling-update percentages, the deployment circuit breaker, alarm-based rollback, blue-green and canary.
- Autoscaling: on CPU or on requests per task.
- How services call each other: Service Connect, an internal ALB or Cloud Map.
- The delivery flow: Terraform for the foundations, GitHub Actions deploying new versions over OIDC, least privilege.
- 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:
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.
| Option | What you manage | Fits | Why | When not to use it |
|---|---|---|---|---|
| EC2 instances (+ Auto Scaling Group) | Operating system, patching, deploy scripts; the unit of scaling is a whole machine | Legacy systems not yet containerised, special kernel settings or hardware, large steady monoliths | The most control; with steady load and a Savings Plan, the lowest cost per unit of compute | Many small services scaling separately, frequent deploys; nobody on the team wants to manage an operating system |
| Elastic Beanstalk | The application and platform version settings | A single web application (Java, Python, Node.js, Go or Docker) that needs to go live quickly | Builds the EC2 instances, Auto Scaling Group and load balancer for you | Several microservices calling each other, fine control over deployment and networking; it is still EC2 underneath, on its platform-update schedule |
| ECS on Fargate | Task definitions and service settings; no machines | A handful to a few dozen containerised services, minimal operations wanted, AWS lock-in acceptable | No nodes to manage; each task gets its own network interface and security group; native ALB, IAM and CloudWatch integration | You need DaemonSets, Operators or Kubernetes-ecosystem tools, or the same setup across clouds |
| EKS (Kubernetes) | Cluster add-ons, node strategy, Kubernetes resources | Already on Kubernetes, many services, GitOps and the Operator ecosystem wanted | The standard Kubernetes API, which largely carries over to other clouds | A small team, few services, nobody owning cluster upgrades |
| Lambda | Function code and its triggers | Event-driven work, sparse traffic, or tall but short spikes: processing S3 uploads, scheduled batches, receiving webhooks | No requests, no charge; scaling is handled by AWS | Long-lived connections (long-running broker subscriptions, a resident connection pool), jobs over 15 minutes, steady high traffic all day |
| S3 + CloudFront | Static files and cache rules | Static front-end sites, single-page applications, documentation sites | No servers; the CDN answers close to the user; very low cost | Pages 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.
orderandpaymentconsume 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:
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.
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.
| Endpoint | Type | Why it is needed |
|---|---|---|
com.amazonaws.<region>.ecr.api | Interface endpoint | Getting the ECR login token and image metadata |
com.amazonaws.<region>.ecr.dkr | Interface endpoint | The registry API used to pull images |
com.amazonaws.<region>.s3 | Gateway endpoint | Image layers are actually stored in S3; gateway endpoints cost nothing extra |
com.amazonaws.<region>.logs | Interface endpoint | awslogs writing to CloudWatch Logs |
com.amazonaws.<region>.secretsmanager | Interface endpoint | Reading 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.
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:
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
ordertasks 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:
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.
| Role | Used by | When | What the shop needs |
|---|---|---|---|
Task execution role (executionRoleArn) | The ECS/Fargate agent | Before the task starts; log writes | Pull 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 runs | Depends 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:
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:
cpu | Allowed 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 up | Wider 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).
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:
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=30Then 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.jsonWhy these fields:
- Three private subnets, three tasks. ECS spreads tasks across Availability Zones by default;
availabilityZoneRebalancingspreads 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
/readyzand decides “should requests go to this task”; the container health check calls/livezand decides “is this process stuck and in need of replacing”. Keeping them apart means that when the database is briefly unreachable,/readyzfails 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/readyzreturns 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:
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.
- 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). - SIGTERM (STOPPING). When deregistration completes, ECS sends SIGTERM to the container.
- SIGKILL. If the program has not exited after
stopTimeout, it is killed.
So the two numbers fit together like this:
deregistration_delayshould be a little longer than the longest normal request, and no more. The shop’s slowest call ispaymentcalling 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.
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 deployment | Fits |
|---|---|---|
| 100% / 200% | Start up to 3 extra new tasks; stop old ones once they are healthy | Production: capacity never drops below 3; briefly paying double |
| 50% / 100% | Stop 1 old task, start 1 new one, and repeat | Development, or plenty of spare capacity: no extra cost, but capacity dips |
| 100% / 150% | Start 1 extra new task at a time | Many 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-gatewayThat 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
}| Metric | Fits | Why | Doesn’t fit |
|---|---|---|---|
ECSServiceAverageCPUUtilization | Most synchronous APIs (order, payment) | Load on a Go service usually shows up first in CPU | Services that mostly wait on external APIs: low CPU but already saturated |
ALBRequestCountPerTarget | api-gateway, which sits directly behind the ALB | Requests react earlier than CPU; the target converts directly from a load test | Services not behind the ALB; services whose per-request cost varies a lot |
ECSServiceAverageMemoryUtilization | Rarely used on its own | Go does not give memory back as soon as load drops, so scaling in is sluggish | Ordinary 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-actionwith--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 limithas to fit within PostgreSQL’smax_connections, for the same reason as on EKS. - Fargate Spot. Interruptible work (such as background batches) can use the
FARGATE_SPOTcapacity provider at a much lower price, but AWS gives only two minutes’ notice before reclaiming the capacity. Synchronous services likepaymentstay on regular Fargate, or at least use the capacity provider strategy’sbaseto 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:
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.
| Approach | How it works | Fits | Cost or limits |
|---|---|---|---|
| Service Connect | ECS adds a proxy container to each task; names are registered in Cloud Map | Services 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 record | Callers outside ECS (for example a legacy system on EC2) | Depends on DNS caching and TTLs; no load balancing, retries or metrics |
| Internal ALB | A non-public ALB in front of each service | When ALB routing rules are needed, or calls cross VPCs | One 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
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-stabilitymakes 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:
| Source | Metric | What it tells you |
|---|---|---|
| ALB | HTTPCode_Target_5XX_Count, TargetResponseTime | Whether users are affected; the deployment rollback alarm uses this |
| ALB target group | UnHealthyHostCount, RequestCountPerTarget | Whether tasks are failing health checks; whether scaling keeps up |
| ECS service | CPUUtilization, MemoryUtilization | Whether the task size is right; the basis for autoscaling |
| ECS events | Service events, stoppedReason of stopped tasks | Why tasks were replaced: failed health checks, OOM, image pull failures |
| Container Insights | Per-task CPU, memory, network | Per-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 withX86_64in the task definition exits immediately, with onlyexec format errorin the logs. Always pass--platformwhen building. - Using
CMD-SHELLfor 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 usesecrets. - 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_delayat 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’sstopTimeoutis at most 120 seconds. healthCheckGracePeriodSecondstoo 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_definitionanddesired_count. The nextterraform applysilently reverts the service to an old version and knocks the replica count back to the minimum. iam:PassRoleon*. 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;
runtimePlatformmatching the image’s architecture; secrets insecrets, read only at start-up; health checks inCMDform calling the program’s own subcommand. - The stop sequence is deregister from the target group, then SIGTERM, then SIGKILL after
stopTimeout;deregistration_delayslightly longer than the longest request, the Go shutdown budget shorter thanstopTimeout. - 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_definitionanddesired_count; CI exchanges OIDC for temporary credentials, andiam:PassRoleis limited by role and service.
References
- Amazon ECS task definition parameters for Fargate (official AWS documentation):
stopTimeout, the logmodeand container health checks, used in the task definition in step 5. - Amazon ECS task execution IAM role (official AWS documentation): the execution role pulling images, reading secrets and writing logs, one of the two roles in step 3.
- Amazon ECS task IAM role (official AWS documentation): the task role used by the application to call AWS APIs, the other role in step 3.
- Pass sensitive data to an Amazon ECS container (official AWS documentation): injecting secrets from Secrets Manager or Parameter Store, behind
secretsin step 5. - How the Amazon ECS deployment circuit breaker detects failures (official AWS documentation): how the deployment circuit breaker counts failures and rolls back, used in step 7.
- Edit target group attributes for your Application Load Balancer (official AWS documentation): the 300-second default
deregistration_delay, behind the shutdown order in step 6. - Use Service Connect to connect Amazon ECS services with short names (official AWS documentation): calling services by short names within a namespace, used in step 9.
- AWS App Runner availability change (official AWS documentation): App Runner closing to new customers and the move to ECS Express Mode, mentioned in step 1.
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.