ECS Fargate troubleshooting

ECS Fargate task keeps stopping? Find the cause and fix it

Your container runs on your laptop. On AWS, it starts, stops and gets replaced. Follow the stopped-task details to the application error, then check that your fix holds.

By Published 25 November 2026Updated 28 November 20269 minute read

“Essential container in task exited” tells you what stopped. The exit code and application log help explain why.

Start with the failed task, its named container and the log from the same attempt. A replacement task has a different ID and may already be hiding the failure you need to inspect.

Start with the task that stopped

A task is the group of containers ECS runs together. If a container marked as essential stops, ECS stops the other containers in that task too. A service then tries to maintain its requested number of tasks, which can create a repeating start-and-stop pattern. AWS explains the essential container setting in its task definition reference.

In the ECS console, open your cluster, choose Tasks and filter for Stopped. Open a failed task and record its stop time, task definition revision, stopped reason and container exit codes. Check the service’s events around the same time.

Save these details promptly. AWS documents a one-hour window for stopped tasks in the console. Its stopped-task guide shows where to find the information.

Read the failure details without changing the service

With the AWS CLI installed, use an authorised profile that can read the relevant ECS details. Replace the profile, region, cluster and service below. Check that the account ID returned by the first command is the account you intended to inspect.

ECS_PROFILE="your-read-only-profile"
ECS_REGION="us-east-1"
ECS_CLUSTER="your-cluster"
ECS_SERVICE="your-service"

aws sts get-caller-identity \
  --profile "$ECS_PROFILE" --region "$ECS_REGION" \
  --query Account --output text

aws ecs list-tasks \
  --profile "$ECS_PROFILE" --region "$ECS_REGION" \
  --cluster "$ECS_CLUSTER" --service-name "$ECS_SERVICE" \
  --desired-status STOPPED --output table

Choose the ARN—the task’s full identifier—from the failed attempt you are investigating. The list is not a promise that the first result is the newest failure. Paste the chosen ARN below.

ECS_TASK_ARN="paste-the-stopped-task-arn-here"

aws ecs describe-tasks \
  --profile "$ECS_PROFILE" --region "$ECS_REGION" \
  --cluster "$ECS_CLUSTER" --tasks "$ECS_TASK_ARN" \
  --query '{failures:failures,tasks:tasks[].{task:taskArn,definition:taskDefinitionArn,stopCode:stopCode,stoppedReason:stoppedReason,stoppedAt:stoppedAt,containers:containers[].{name:name,exitCode:exitCode,reason:reason,imageDigest:imageDigest}}}' \
  --output json

These commands read account and task information. If tasks is empty, check failures, the account, region, cluster and task ARN. The task record may also have expired. The DescribeTasks response includes both task results and lookup failures.

  • stopCode and stoppedReason: the task-level explanation, such as an essential container ending or the service stopping the task.
  • Container name, exitCode and reason: which process ended and any extra detail ECS recorded. An exit code may be absent if the container never started.
  • Task definition and image digest: the configuration revision and exact image involved. Compare them with the last working release.

Connect the exit code to the application log

Open the failing container’s log stream for that task ID and time. With the awslogs driver configured, the application’s standard output and error output are sent to CloudWatch Logs. AWS describes the required setup in its container logging guide.

Suppose the application ends with code 1 and logs:

Startup failed: APP_MESSAGE is required.

That message identifies the missing setting. Check whether it reaches the failing container in the new task definition. Increasing memory or starting another identical task will not supply it.

If there is no application log, check the stopped reason first: the container may have failed before the application ran. Also check the log configuration, destination and task execution role’s logging permissions. Use the failed task’s records; ECS Exec operates on running containers.

Reproduce a missing-setting failure on your computer

This small Python application requires a non-secret greeting called APP_MESSAGE. Without it, startup ends with code 1. With it, the application serves a greeting and a health response.

One setting changes the startup result

Setting missing

  1. Application starts.
  2. It reports the missing setting.
  3. It exits with code 1.

Setting supplied

  1. Application checks its setting.
  2. The web server starts.
  3. A health request returns 200.

Use Python 3 in a separate test environment. Save the following as app.py. It listens only on your computer at 127.0.0.1 and uses no AWS credentials. Read our code usage and safe-use terms before running it.

# Copyright 2026 Anrotex IT Systems LLP.
# Learning and evaluation only: https://www.anrotex.com/downloads-policy
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

message = os.environ.get("APP_MESSAGE", "").strip()
if not message:
    print("Startup failed: APP_MESSAGE is required.", file=sys.stderr)
    raise SystemExit(1)


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path not in ("/", "/health"):
            self.send_error(404)
            return
        body = ("ok\n" if self.path == "/health" else message + "\n").encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


port = int(os.environ.get("DEMO_PORT", "18080"))
with HTTPServer(("127.0.0.1", port), Handler) as server:
    print(f"Listening on http://127.0.0.1:{server.server_port}", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass

In a macOS or Linux terminal, run it without the setting:

env -u APP_MESSAGE python3 app.py
echo $?

The application reports the missing setting, and the next command prints its exit code:

Startup failed: APP_MESSAGE is required.
1

Supply the setting and check the response

Run the same file with the setting supplied. Keep this terminal open while you check the application.

APP_MESSAGE=hello DEMO_PORT=18080 python3 app.py

It reports Listening on http://127.0.0.1:18080. In a second terminal, request both the health endpoint and the greeting:

curl --fail --silent --show-error http://127.0.0.1:18080/health
curl --fail --silent --show-error http://127.0.0.1:18080/
ok
hello

Both requests return HTTP 200. Repeat them while the application remains running, then press Ctrl+C in the first terminal to stop it. If port 18080 is already occupied, choose another unused port and use it in both curl commands.

The failure message and successful responses above come from this local Python example. Use this small server for the exercise; your deployed application should use its usual production server.

Apply the same diagnosis to your ECS application

If your own application log identifies a missing non-secret setting, add it to the correct container’s environment list through your usual task-definition or infrastructure code process. For this greeting example, the entry would be:

"environment": [
  { "name": "APP_MESSAGE", "value": "hello" }
]

Keep the other container settings and existing environment entries. Register a new task definition revision and test it in staging before changing production. An existing running container does not pick up a newly registered revision automatically. Use your approved secret store for passwords and tokens, and keep their values out of logs and screenshots.

For a web application on ECS, also check that its server listens on the configured container port and an interface reachable by the load balancer, usually 0.0.0.0. The local exercise above intentionally binds to your computer’s loopback address.

When the evidence points to another cause

The same short error message can accompany different failures. Use the exit code together with the stopped reason, logs and service events.

What you seeWhat to investigateWhat would support the fix
Exit code 0The command completed successfully. A setup script may have finished without starting the long-running web process. Completion can be normal for a one-off job.The intended service process remains running and answers requests.
Exit code 1An application error. Read the first useful error around startup: missing configuration, a failed dependency or an invalid command.The identified error is resolved and the same startup path succeeds.
Exit code 137The process was killed. Look for an out-of-memory reason and memory metrics, or a forced stop after the shutdown timeout.Evidence identifies why it was killed; the application passes a representative test after the change.
CannotPullContainerError or ResourceInitializationErrorImage retrieval or startup preparation. Follow the specific reason for registry access, networking, secrets or logging setup.The task reaches application startup and produces the expected logs.
Service events report failed health checksCheck the load balancer path, port, response, network access and startup timing. A container can be running while the service is unreachable.Both the application check and the load balancer target check pass.

Code 137 alone does not prove a memory shortage. Match it to the out-of-memory reason, available memory measurements and shutdown events before changing capacity. A process can also be forcibly stopped when it does not finish within the configured stop timeout.

For failed health checks, test the exact configured check. A container health check runs inside the container, while a load balancer checks the application over the network. They can fail for different reasons.

If image pulls, logs or secrets fail after a network change, trace the routes in our Fargate NAT gateway and private endpoint guide.

Check that the ECS release stays healthy

Once the cause is understood, review the proposed change and deploy it to the agreed test environment. Keep the last compatible working revision available while validating the new one.

  1. Confirm the version. Check the task definition revision and image digest on the new task.
  2. Check the startup log. Confirm the earlier error is gone and required dependencies connect.
  3. Check both health paths. Test the configured container check, if present, and the load balancer target status.
  4. Make a real application request. A basic health response may not exercise a database or other important dependency.
  5. Watch for replacement tasks. Allow enough time for your configured startup and health-check intervals, and exercise representative traffic. Repeated task replacement means the investigation is still open.
  6. Check the alert. In staging, use an agreed failure test to confirm the alert reaches the person responsible for recovery.

Keep the task ID, failed revision, useful log line, change and verification result together. For failures that disappear before someone can investigate, consider ECS event capture with an agreed retention period and cost. Avoid putting credentials or customer data into an incident note.

Our release checklist helps record the tested version, health checks, recovery steps and owner before the next rollout.

Choose the help that fits your situation

For an existing ECS service that keeps failing, start with DevOps consulting. Share the symptom, recent changes and the outcome you need. We agree the investigation and implementation scope before work starts.

If releases repeatedly introduce configuration mistakes, explore CI/CD automation for checks before and after deployment. For a new stateless application that needs AWS infrastructure, see the scope of our Terraform AWS Foundation.

Discuss your ECS deployment