
A service on Amazon ECS says 2 of 3 tasks running. A minute later it says 3 of 3. Something stopped a task and ECS replaced it, and unless you were looking at the right page at the right moment, you never saw why.
That is the core problem with monitoring ECS, and with Fargate in particular. There is no server to log in to and no host agent to install. ECS restarts tasks for you, which is good for uptime and bad for knowing what is going on. This guide covers where ECS records why a task stopped, the four failures that matter most (OOM kills, image pull errors, tasks that keep stopping and failed deployments), and how to get an alert for each.
We build Webalert, which has an ECS monitor; it comes up near the end. Everything before that works with the AWS CLI alone.
Where ECS says why a task stopped
When a task stops, ECS records the reason on the task itself:
stopCode: the kind of stop, such asTaskFailedToStart,EssentialContainerExited,ServiceSchedulerInitiated(a deploy or scale-in replaced it) orSpotInterruption.stoppedReason: a sentence from ECS, such as "Essential container in task exited" or "Task failed ELB health checks in (target-group ...)".- For each container,
exitCodeandreason: this is whereOutOfMemoryErrororCannotPullContainerErrorshows up.
The catch: ECS only keeps stopped tasks visible for a short time, about an hour. Read them while they are there:
# The service's recently stopped tasks
aws ecs list-tasks --cluster prod --service-name checkout --desired-status STOPPED
# Why each one stopped
aws ecs describe-tasks --cluster prod --tasks <task-arn> \
--query 'tasks[].{stopCode:stopCode,why:stoppedReason,containers:containers[].{name:name,exit:exitCode,reason:reason}}'
# The service's own story: deployments, placement problems, health checks
aws ecs describe-services --cluster prod --services checkout \
--query 'services[0].events[:10].[createdAt,message]' --output table
If you want a lasting record without any tool, an EventBridge rule on "ECS Task State Change" events with lastStatus STOPPED can send each stopped task to a log group or an SNS topic. That gives you a record, but an alert per stopped task gets noisy fast: a single bad deploy can stop dozens of tasks.
OOM kills: exit code 137 and OutOfMemoryError
On ECS an out-of-memory kill looks like this on the stopped task:
stopCode:EssentialContainerExitedstoppedReason: "Essential container in task exited"- the container's
exitCode:137, and itsreason:OutOfMemoryError: Container killed due to memory usage
137 is 128 + 9: the process was killed with SIGKILL. It got no chance to log anything, so your application logs just stop. The container's reason is what tells you it was memory.
Where the limit comes from. On Fargate, the task definition's task-level memory is the hard ceiling for all containers in the task. A container can also have its own hard memory limit, and memoryReservation is a soft reservation that is not enforced as a limit. A container is killed when it goes over its own hard limit, or when the task as a whole runs out.
Exit code 137 without OutOfMemoryError is usually not memory at all. When ECS stops a task during a deploy or a scale-in, it sends SIGTERM, waits for the container's stopTimeout (30 seconds by default on Fargate) and then sends SIGKILL. An app that ignores SIGTERM exits with 137 every time it is replaced. The stopCode there is ServiceSchedulerInitiated, and the fix is to handle SIGTERM, not to add memory.
How to fix a real OOM kill:
- Look at memory over time. The
AWS/ECSCloudWatch metricMemoryUtilization(byClusterNameandServiceName) is a percent of the memory the task definition reserves. Watch the maximum, not only the average: one task near 100% hides well in an average of three. - Spike or leak? A steady climb over hours is a leak, and raising the limit only moves the kill later. A jump under load is a spike: a big request, a large batch or an unbounded cache.
- Size the runtime to the container. Set heap limits explicitly so the runtime fits inside the task (for example
-XX:MaxRAMPercentagefor the JVM or--max-old-space-sizefor Node.js). - Raise the task's memory when the app really needs more. On Fargate only some CPU and memory combinations are valid, so a bigger memory size can mean a bigger CPU size too.
The Kubernetes version of this problem is covered in Kubernetes OOMKilled and exit code 137.
CannotPullContainerError: tasks that can't start
When a task can't get its image, it never runs. The stopped task has stopCode TaskFailedToStart and a container reason that starts with CannotPullContainerError. The rest of the message usually says which of these it is:
- The image or tag doesn't exist. A typo, a tag that was never pushed, or an image deleted by an ECR lifecycle policy. The message says "not found".
- No route to the registry. A Fargate task in a public subnet needs a public IP (
assignPublicIp=ENABLED) to reach the internet. In a private subnet it needs a NAT gateway, or VPC endpoints for ECR (ecr.apiandecr.dkr, plus an S3 gateway endpoint for the image layers). The message often ends in a timeout. - The execution role can't pull. The task execution role pulls the image, not the task role. The AWS managed
AmazonECSTaskExecutionRolePolicyallows pulls from ECR. A private registry outside ECR needsrepositoryCredentialsandsecretsmanager:GetSecretValueon that secret. - Rate limits. Anonymous pulls from Docker Hub are rate limited; the message says "toomanyrequests". Copy base images into ECR, or authenticate.
- The wrong CPU architecture. An image built only for
amd64won't run on anARM64task, and the other way round.
A close relative is ResourceInitializationError: the task couldn't fetch its secrets from SSM Parameter Store or Secrets Manager, or its registry credentials. The causes are the same two: no route to the service, or an execution role without the permission.
While the image can't be pulled, the service keeps trying to start new tasks, and after repeated failures ECS starts throttling its launch attempts. Nothing is down yet if the old tasks still run, but nothing new can start either: no deploy, no scale-out, no replacement for a task that dies.
The Kubernetes version is ImagePullBackOff and ErrImagePull.
Tasks that keep stopping
ECS has no CrashLoopBackOff state, but it has the same problem: a task starts, stops, gets replaced, and stops again. The service shows "running" most of the time, so a dashboard that samples the task count can miss it entirely. The stopped tasks show one of two patterns:
- An essential container exited with an error.
stopCodeEssentialContainerExitedand a non-zero exit code such as 1. The app crashed: a missing environment variable, a database it can't reach at start, a bad config. Its own logs (with theawslogsdriver, in CloudWatch Logs) say why. - Health checks failed. "Task failed ELB health checks" means the load balancer target group marked the task unhealthy; "Task failed container health checks" means the task definition's own
healthCheckdid. A slow-starting app is often killed before it is ready: sethealthCheckGracePeriodSecondson the service, orstartPeriodon the container health check, to cover the start-up time.
Three or more of these in ten minutes is a pattern, not bad luck. The CrashLoopBackOff guide covers the same debugging from the Kubernetes side.
Failed deployments and circuit breaker rollbacks
With the deployment circuit breaker on, ECS watches a rolling deployment. If its new tasks keep failing to start or to pass health checks, ECS marks the deployment FAILED. With rollback on, it then goes back to the last deployment that completed:
aws ecs update-service --cluster prod --service checkout \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}"
This is a good default, and it has one trap. After a rollback the service runs the old version with all its tasks healthy. Every task count looks fine. The only signs are the deployment's rolloutState of FAILED, a service event saying the deployment failed, and the new code that never shipped. If your pipeline doesn't wait for the deployment to finish (for example with aws ecs wait services-stable), the job can go green and nobody notices that the release didn't happen.
So a failed deployment deserves its own alert, separate from tasks being down. EventBridge emits an "ECS Deployment State Change" event with SERVICE_DEPLOYMENT_FAILED that you can route, or you can read the deployments from describe-services. ECS can also roll back on CloudWatch alarms (deploymentConfiguration.alarms), which catches a deploy that starts fine but raises your error rate.
A service short of tasks
The last thing to watch is the simplest: fewer running tasks than desired, for longer than a deploy takes. Common causes on Fargate:
- tasks failing for one of the reasons above;
- no room to place tasks: a subnet out of free IP addresses (each Fargate task takes one), the account's Fargate vCPU quota, or no Fargate Spot capacity at the moment;
- a dependency that the tasks need at start, such as a secret or a database, being unavailable.
Ten minutes is a sensible threshold: long enough to ignore a normal rollout, short enough to matter. CloudWatch only has a running task count per service with Container Insights turned on (RunningTaskCount in ECS/ContainerInsights), which AWS bills separately. Without it, read runningCount and desiredCount from describe-services.
What to alert on
| Failure | Where it shows | Alert when |
|---|---|---|
| OOM kill | container reason OutOfMemoryError, exit code 137 |
any task of the service, once |
| Tasks can't start | stopCode TaskFailedToStart, CannotPullContainerError, ResourceInitializationError |
it happens twice in 10 minutes |
| Tasks keep stopping | non-zero exit codes, failed ELB or container health checks | 3 or more in 10 minutes |
| Short of tasks | runningCount below desiredCount |
for 10 minutes |
| Deployment failed | deployment rolloutState FAILED, circuit breaker |
every time |
And what not to alert on: tasks stopped by a deploy, by a scale-in or by a Spot interruption. ECS replaces those on purpose.
Two more rules make the difference between useful and noisy. One incident per service and cause, not one per task: a bad image tag stops every new task, and that is one problem. And one cause wins: an OOM kill also leaves the service short of tasks, and the alert should say OOM, not both. Keep an outside-in uptime check on the service's URL as well. It tells you whether users noticed, which decides how urgent the incident is.
How Webalert monitors ECS and Fargate
Webalert reads an ECS cluster with one small task in the cluster itself, the ECS reader. It runs on Fargate (ARM64, 0.25 vCPU, 0.5 GB) and works the same for clusters on Fargate, on EC2 or both. You don't change your own task definitions or add a sidecar.
Setup. Under Servers, Add server, Amazon ECS, name the group after the cluster and get its key. Then, in AWS CloudShell in the cluster's account and region, the app gives you lines that put the key in SSM Parameter Store as a SecureString and deploy Webalert's CloudFormation template:
aws ssm put-parameter --name /webalert/prod/group-key --type SecureString --overwrite \
--value 'wag_…'
curl -fsSLO https://web-alert.io/agent/ecs/webalert-ecs-reader.yaml
aws cloudformation deploy --stack-name webalert-reader-prod --template-file webalert-ecs-reader.yaml \
--capabilities CAPABILITY_IAM --parameter-overrides ClusterName=prod \
GroupKeyParameter=/webalert/prod/group-key VpcId=$VPC Subnets=$SUBNETS AssignPublicIp=ENABLED
The stack creates the reader's service, its two roles, a log group and a security group with no inbound rules. Terraform and a plain task definition are there too, if CloudFormation isn't how you work. EC2 container instances, if the cluster has any, can also run the agent for their host metrics and Docker containers: one line in the launch template.
What it alerts on is the table above, per service, with one incident per cause and the highest cause first: a task OOM-killed (with the container and its memory in the title), tasks that can't start, tasks that keep stopping, a service short of tasks for 10 minutes, and a deployment the circuit breaker stopped. A recovery says what is true now, such as "checkout has 3 of 3 tasks running again in prod". If the reader itself stops reporting, you get one alert for that, since no other alert in the cluster can fire without it. The alerts go to your channels or page whoever is on call.
What you see. A Services tab with each service's tasks, deployments and last events, and its stopped tasks with their cause, exit codes and reason. Charts of each service's CPU and memory (average and busiest task), tasks running against desired, and stopped tasks by cause. With AI SRE (beta), the diagnosis of an incident gets the service's stopped tasks, events and the last hour of CPU and memory.
What it can read. The reader's task role allows ecs:ListServices, ecs:DescribeServices, ecs:ListTasks, ecs:DescribeTasks and cloudwatch:GetMetricData, and nothing else. It never reads task definitions, environment variables, task overrides or logs, and no AWS keys leave your account. What leaves is numbers, service names, deployments and events, and why tasks stopped, with the reasons redacted first.
What it costs. Each ECS service with running Fargate tasks counts as one server: €3 a month on Starter or Business, averaged over 30 days. Services on EC2 are covered by their instances and never count twice. The reader is free. On the AWS side, at list price, the reader task is about USD 7 a month (plus about USD 3.60 for a public IP, if it has one), and the CloudWatch reads are about USD 0.17 per service a month.
The full setup, the network it needs and how to change the key are in the ECS docs. If you also run Kubernetes, see Kubernetes monitoring.
FAQ
Can I install a monitoring agent on Fargate?
Not on a host, because Fargate has none you can reach. The usual options are a sidecar container in every task definition, polling AWS from outside with an IAM role, or one task in the cluster that reads the ECS API. Webalert uses the last: one read-only task per cluster, with no change to your own tasks.
What does exit code 137 mean on ECS?
The container was killed with SIGKILL. If its reason says OutOfMemoryError, it ran out of memory. If the stop code is ServiceSchedulerInitiated, ECS was replacing it and the app didn't exit within its stop timeout after SIGTERM.
How long does ECS keep stopped tasks?
Only for a short time, about an hour, in the console and the API. To keep a record, read them as they happen, or send "ECS Task State Change" events from EventBridge to a log group.
Does the deployment circuit breaker alert me?
No. It marks the deployment FAILED and, with rollback on, returns the service to the last working deployment. Nothing tells you unless you route the "ECS Deployment State Change" event or read the deployment state yourself.
Does Webalert work for ECS on EC2?
Yes. The ECS reader reads the services and tasks of any ECS cluster. The EC2 container instances can also run the Webalert agent for their CPU, memory, disks and Docker containers; each instance counts as a server, and services that run on them don't count again.