Sub topic 18
Diagnosing failed tasks and using ECS Exec
This chapter assumes you can read a Fargate task definition, you know the difference between the task execution role and the task role, and you have a service running behind an Application Load Balancer. It covers where to look when a task fails, what the common failure messages mean, and how to open a shell in a running container with ECS Exec.
Start with the stopped reason
When a task stops, ECS records why. Stopped tasks stay visible for about an hour, so check quickly. You can see them in the console under the cluster's Tasks tab (filter by "Stopped"). You can also use the CLI:
aws ecs list-tasks --cluster demo --desired-status STOPPED
aws ecs describe-tasks \
--cluster demo \
--tasks arn:aws:ecs:us-east-1:123456789012:task/demo/0123456789abcdef0 \
--query "tasks[0].{stopCode:stopCode,reason:stoppedReason,containers:containers[].{name:name,exit:exitCode,reason:reason}}"Three fields matter most:
stopCodeis a category such asTaskFailedToStart,EssentialContainerExited, orServiceSchedulerInitiated.stoppedReasonis the human-readable message for the task as a whole.- Each container has its own
exitCodeandreason.
Read them in that order. The stop code tells you whether the failure happened before your code ran or after.
Failures before the container starts
If the task never reaches RUNNING, your application code has not executed. The cause is almost always configuration around it.
CannotPullContainerError
Fargate could not download the image. Check these in order:
- The image URI and tag exist in ECR. A typo in the tag is the most common cause.
- The task execution role has
AmazonECSTaskExecutionRolePolicy, which includes the ECR pull permissions. - The task has a network path to ECR. A task in a private subnet with
assignPublicIp=DISABLEDneeds a NAT gateway or VPC endpoints. ECR needsecr.apiandecr.dkrinterface endpoints, plus an S3 gateway endpoint because image layers are stored in S3. If you use theawslogsdriver, add a CloudWatch Logs endpoint as well. - Security group egress allows HTTPS (port 443) to those destinations.
A task in a public subnet with assignPublicIp=ENABLED can also pull images through the internet gateway. Use that only for experiments.
ResourceInitializationError
This error means ECS could not set up something the task needs before starting. The message usually names the resource. Typical causes:
- The execution role cannot read the Secrets Manager secret or SSM parameter listed in
secrets. It needssecretsmanager:GetSecretValue(andkms:Decryptif the secret uses a customer managed key). - The secret ARN is wrong, or the secret is in another Region.
- The task cannot reach Secrets Manager, SSM, or an EFS mount target because of a missing endpoint or security group rule.
Note that secrets are fetched with the execution role, not the task role. Adding permissions to the task role does not fix this error.
Capacity and network placement errors
Service events can show messages such as "unable to place a task" or failures to create a network interface. The usual causes are subnets that have run out of free IP addresses, because every awsvpc task uses one IP address, or a Fargate Spot request that could not be satisfied. Look at the service events:
aws ecs describe-services \
--cluster demo \
--services web \
--query "services[0].events[:10].[createdAt,message]" \
--output tableFailures after the container starts
Exit codes
If the task started and then stopped, the container exit code is your first clue.
| Exit code | Usual meaning |
|---|---|
| 0 | The process finished normally. For a long-running service, this means the process ended when it should not have. |
| 1 | The application raised an error. Read the logs. |
| 137 | The container was killed with SIGKILL. The task often ran out of memory, or ECS stopped it after it ignored SIGTERM. |
| 139 | Segmentation fault in the process. |
| 143 | The process stopped after SIGTERM, which is normal during a deployment or scale-in. |
With code 137, check the reason field. OutOfMemoryError: Container killed due to memory usage confirms an out-of-memory kill. Raise the task memory, or set the container memory hard limit correctly, and look for leaks.
An exit code of 255 or an exec format error in the logs often means an architecture mismatch. An image built for ARM64 on a Mac will not run on a task whose runtimePlatform says X86_64. Build for the right platform, or change cpuArchitecture.
Read the logs
If the container wrote anything, it is in CloudWatch Logs under the group and stream prefix from logConfiguration. Stream names follow the pattern prefix/container-name/task-id. To follow them from a terminal:
aws logs tail /ecs/web-app --follow --since 30mIf the log group is empty, suspect one of these:
- The log group does not exist. The
awslogsdriver does not create it unless you setawslogs-create-grouptotrueand the execution role haslogs:CreateLogGroup. - The execution role lacks
logs:CreateLogStreamorlogs:PutLogEvents. - The application crashed before writing anything, for example a wrong
entrypoint.
Health check failures and restart loops
A service that starts tasks and keeps replacing them is usually failing a health check. Distinguish the two kinds:
- The target group health check decides whether the ALB sends traffic to the task. If it fails past the grace period, the service scheduler stops the task and starts another.
- The container health check runs inside the container. If it fails after
retriesattempts, the container is markedUNHEALTHY, and ECS replaces the task if the container is essential.
Frequent causes are a wrong port in the target group, a health path that returns a redirect or a 401, a security group that does not allow the ALB to reach the task port, a container health check that uses curl when the image does not include it, and a start-up time longer than healthCheckGracePeriodSeconds or startPeriod. If a task stops with the message "Task failed ELB health checks", test the health path first and increase the grace period only if the application is simply slow to start.
When a bad deployment loops, the deployment circuit breaker stops it after repeated failed launches and rolls back to the previous task definition. The service events show deployment failed messages when this happens.
Using ECS Exec
Logs show what the application chose to say. Sometimes you need to look inside the container: check environment variables, test DNS, or call another service from the task's network position. ECS Exec does this without opening SSH or running a bastion host. It uses the SSM Session Manager channel, so no inbound ports are needed.
Requirements
- The task role (not the execution role) allows the SSM messages actions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Resource": "*"
}
]
}- The service or task is started with exec enabled.
- The task can reach the
ssmmessagesendpoint, by NAT or by a VPC interface endpoint. - The container image contains the shell or tool you want to run. Minimal images such as
scratchor distroless have no/bin/sh. - The Session Manager plugin is installed on the machine where you run the CLI.
- Your own IAM identity is allowed to call
ecs:ExecuteCommand.
Enabling and connecting
Enabling exec on an existing service applies only to new tasks, so force a new deployment:
aws ecs update-service \
--cluster demo \
--service web \
--enable-execute-command \
--force-new-deployment
aws ecs execute-command \
--cluster demo \
--task 0123456789abcdef0 \
--container web \
--interactive \
--command "/bin/sh"If you get TargetNotConnectedException, one of the requirements above is missing. The usual culprits are the task role permissions, a missing network path to ssmmessages, or a task that started before exec was enabled. You can run a check script from the AWS amazon-ecs-exec-checker project to test most of these at once.
A short diagnosis routine
- Run
describe-taskson a stopped task and readstopCode,stoppedReason, and the container exit code. - If the task never started, check the image URI, the execution role, secret ARNs, and the network path.
- If it started, read CloudWatch Logs.
- If the service loops, compare the target group health check with what the container actually serves.
- If the logs are not enough and the task is running, use ECS Exec.
Exercise
A new service keeps launching tasks that stop within a minute. stoppedReason says "ResourceInitializationError: unable to pull secrets or registry auth", and the secret ARN in the task definition is correct. A teammate adds secretsmanager:GetSecretValue to the task role, but the error stays. What should you change, and what network setting might also be responsible?
Show answer
Add the permission to the task execution role, because ECS uses that role to fetch secrets before the container starts, and add kms:Decrypt if the secret uses a customer managed key. If the role is already correct, check that the task, running in a private subnet, can reach Secrets Manager through a NAT gateway or a VPC interface endpoint, and that its security group allows outbound HTTPS.
Exercise
You enabled ECS Exec on a service with update-service --enable-execute-command, but execute-command on an existing task returns TargetNotConnectedException. Give two likely reasons.
Show answer
The task started before exec was enabled, so you need --force-new-deployment to get tasks with the feature on. The task role may also lack the ssmmessages permissions, or the task may have no network path to the ssmmessages endpoint. A missing shell in the image is another possibility, although that produces a different error once connected.