Amazon ECS Task Definitions, Services, and Deployments Explained

By Oleksandr Andrushchenko — Published on — Modified on

Amazon ECS Task Definitions, Services, and Deployments Explained
Amazon ECS Task Definitions, Services, and Deployments Explained

Amazon ECS task definitions, tasks, services, and deployments are the core runtime model behind ECS. A task definition describes how a container should run, a task is a running copy of that definition, a service keeps tasks alive, and a deployment replaces one version with another.

Understanding these relationships is more important than memorizing ECS console options. Once the task definition → task → service → deployment model is clear, ECS becomes much easier to reason about in production.

Table of Contents

ECS Runtime Model

ECS has a small number of core objects, but they are often confused. A task definition is not a running container. A task is not the same as a service. A service is the controller that keeps tasks running.

The most useful mental model is simple: task definitions describe, tasks run, and services maintain.

Task Definition Revision 7
          │
          ▼
      ECS Service
          │
   Desired Count = 3
          │
 ┌────────┼────────┐
 ▼        ▼        ▼
Task     Task     Task
 │        │        │
Container Container Container
ECS Object Practical Meaning Production Role
Task Definition Versioned runtime blueprint Defines how the application should run.
Task Running copy of a task definition Executes the application container.
Service Controller for tasks Keeps the desired number of tasks running.
Deployment Replacement process Moves a service from one task definition revision to another.

Task Definitions

A task definition is the blueprint ECS uses to start tasks. It describes the container image, CPU, memory, ports, environment variables, secrets, logging, health checks, and runtime behavior.

Task definitions are versioned. Each change creates a new revision, which makes deployments and rollbacks easier to track.

Task Definition Purpose

The purpose of a task definition is to make runtime configuration explicit and repeatable. Instead of manually starting containers with different Docker commands on different machines, ECS starts tasks from a structured definition.

A task definition should answer the main runtime questions: what image should run, how much CPU and memory it needs, which ports are exposed, where logs go, and which configuration values are injected.

{
  "family": "orders-api",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "containerDefinitions": [
    {
      "name": "orders-api",
      "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/orders-api:8f31c2a",
      "essential": true,
      "portMappings": [
        {
          "containerPort": 8000,
          "protocol": "tcp"
        }
      ]
    }
  ]
}

Production Note: task definitions should use immutable image tags such as Git SHA, build number, or release version. Reusing latest makes deployments harder to audit and roll back.

Important Fields

A task definition can contain many options, but only a smaller set matters for most production services. These fields define runtime behavior and strongly affect reliability.

Field Purpose Production Concern
image Container image to run Should be immutable and traceable.
cpu CPU allocation Too low can cause latency under load.
memory Memory limit Too low can cause task termination.
portMappings Container ports Must match load balancer target configuration.
environment Plain configuration Should not contain secrets.
secrets Injected sensitive values Should come from Secrets Manager or SSM.
logConfiguration Container log routing Usually CloudWatch Logs.
healthCheck Container health validation Should be lightweight and reliable.

Task Definition Revisions

Every task definition update creates a new revision. For example, orders-api:7 and orders-api:8 are two versions of the same task definition family.

ECS services deploy by moving from one revision to another. This makes the deployed runtime configuration visible and allows controlled rollback to a previous revision.

orders-api:7
  image: orders-api:8f31c2a
  memory: 1024

orders-api:8
  image: orders-api:91ab77e
  memory: 1024

Key Point: a new Docker image alone does not update a running ECS service. The service must deploy a task definition revision that points to the new image.

Tasks

A task is a running instance of a task definition. If the task definition is the blueprint, the task is the actual running workload created from that blueprint.

Tasks are intentionally replaceable. ECS production design assumes tasks can start, stop, fail, move, and be replaced at any time.

What Is a Task?

A task can contain one container or multiple containers. Many simple APIs use one application container. More advanced designs may include sidecars for proxies, telemetry, log routing, or service mesh behavior.

Task
  Container: application

Task with sidecar
  Container: application
  Container: log-router
  Container: proxy

Containers inside the same task share a lifecycle. If an essential container exits, the task is usually stopped and replaced.

Task Lifecycle

ECS tasks move through lifecycle states. These states help explain what happens during deployments, failures, and service recovery.

State Meaning
PROVISIONING ECS is preparing resources required by the task.
PENDING The task is waiting to start.
RUNNING The task containers are running.
STOPPING The task is being stopped.
STOPPED The task has exited or was terminated.
PROVISIONING
  -> PENDING
  -> RUNNING
  -> STOPPING
  -> STOPPED

Why Tasks Disappear

ECS tasks are not permanent servers. A task may disappear because of a deployment, failed health check, container crash, scale-in event, infrastructure issue, or manual service update.

This is expected behavior. A production ECS application should not depend on a specific task staying alive forever.

Reason What Happens
New deployment Old tasks are replaced by tasks from a new revision.
Container crash The service starts a replacement task.
Failed health check The unhealthy task is removed from service.
Scale-in ECS stops extra tasks after desired count decreases.

Rule of Thumb: store durable state outside the task. Use RDS, DynamoDB, S3, EFS, Redis, or a queue depending on the workload.

ECS Services

An ECS service is the controller that keeps tasks running. It manages desired count, deployments, health replacement, and load balancer registration.

Without a service, a task can run once and stop. With a service, ECS continuously tries to maintain the configured number of healthy tasks.

Service Purpose

The main purpose of a service is to maintain desired state. If the service says three tasks should run, ECS works to keep three healthy tasks running.

ECS Service: orders-api
  Task Definition: orders-api:7
  Desired Count: 3

Actual State:
  Task A: RUNNING
  Task B: RUNNING
  Task C: RUNNING

For web applications, the service can also register tasks with a load balancer target group. This allows traffic to follow healthy tasks instead of fixed server addresses.

Desired Count

Desired count is the number of tasks the service should keep running. It is one of the simplest but most important ECS service settings.

Desired Count Meaning Production Impact
1 One running task No task-level redundancy
2 Two running tasks Basic redundancy for small services.
3+ Multiple running tasks Better during deployments, failures, and traffic spikes.

Production Note: desired count should account for deployments. A service with only one task may have reduced availability during replacement unless deployment settings and health checks are carefully configured.

Self-Healing

ECS services are self-healing at the task level. If a task exits unexpectedly, ECS starts a replacement to restore desired count.

Desired Count = 3

Task A: RUNNING
Task B: STOPPED
Task C: RUNNING

ECS action:
  Start replacement Task D

Result:
  Task A: RUNNING
  Task C: RUNNING
  Task D: RUNNING

Important: ECS can replace failed tasks, but it cannot fix broken application logic. If every new task crashes because of a bad release, ECS will keep trying and the service will remain unhealthy.

ECS Deployments

An ECS deployment replaces one running version of a service with another. In most cases, this means replacing tasks that use an older task definition revision with tasks that use a newer revision.

Deployments are controlled by the ECS service. The service starts new tasks, waits for them to become healthy, and stops old tasks according to deployment configuration.

How Deployments Work

A deployment starts when the service is updated to a new task definition revision. ECS then creates new tasks from the new revision and gradually removes old tasks.

Before deployment:
  Service uses orders-api:7

Deploy:
  Update service to orders-api:8

During deployment:
  Some tasks run orders-api:7
  Some tasks run orders-api:8

After deployment:
  All tasks run orders-api:8

Key Point: during a rolling deployment, two application versions may run at the same time. Database changes, API contracts, and message formats should be compatible with that reality.

Rolling Deployments

A rolling deployment replaces tasks gradually instead of stopping the entire service at once. This allows a service to remain available while a new version is introduced.

Initial state:
  Task A: revision 7
  Task B: revision 7
  Task C: revision 7

Deployment starts:
  Task A: revision 7
  Task B: revision 7
  Task C: revision 7
  Task D: revision 8

After new task is healthy:
  Task B: revision 7
  Task C: revision 7
  Task D: revision 8

Final state:
  Task D: revision 8
  Task E: revision 8
  Task F: revision 8

Rolling deployments work best when tasks start quickly, health checks are reliable, and the application handles graceful shutdown correctly.

Deployment Configuration

Deployment behavior is controlled by service configuration. Two important settings are minimum healthy percent and maximum percent.

Setting Purpose Example Meaning
desiredCount Normal number of running tasks Keep 4 tasks running.
minimumHealthyPercent Minimum healthy tasks during deployment At least 2 of 4 tasks must stay healthy at 50%.
maximumPercent Temporary over-provisioning limit Up to 8 tasks may run at 200%.
healthCheckGracePeriod Startup time before health checks count Useful for slow-starting applications.

Trade-off: higher maximum percent can make deployments safer and faster, but it requires extra temporary capacity. Lower maximum percent reduces capacity needs but can slow deployments.

Updating an Application

Updating an ECS application is more than pushing a new Docker image. ECS must receive a new task definition revision and the service must be updated to use that revision.

This process should be automated through CI/CD. Manual updates are easy to get wrong and hard to audit.

Typical Release Flow

A typical ECS release starts with a code change and ends with healthy tasks running a new task definition revision.

1. Merge code
2. Build Docker image
3. Push image to Amazon ECR
4. Register new task definition revision
5. Update ECS service
6. ECS starts new tasks
7. Health checks pass
8. ECS stops old tasks
9. Deployment completes

Production Note: the image tag, Git commit, task definition revision, and deployment event should be traceable to each other.

Safe Rollout Requirements

ECS can orchestrate replacement, but the application must be safe to replace. Deployment reliability depends on application behavior as much as ECS configuration.

  • Fast startup so new tasks become healthy quickly.
  • Reliable health checks so broken tasks are not added to traffic.
  • Graceful shutdown so old tasks finish in-flight work.
  • Backward-compatible database changes because old and new tasks may overlap.
  • Stable configuration so new tasks do not fail immediately after launch.

Production Design Notes

ECS services are reliable only when the application is designed for replacement. Tasks should be disposable, health checks should be meaningful, and shutdown behavior should be predictable.

The service scheduler provides the control loop, but application design determines whether replacement is safe.

Stateless Tasks

ECS tasks should usually be stateless. A task can stop during deployment, scaling, host replacement, or health recovery.

Durable state should be stored outside the task. Local container storage is temporary and should not hold important user data.

State Type Better Location
User records RDS or DynamoDB
Uploaded files S3
Sessions Redis or signed stateless tokens
Background work SQS or another queue

Health Checks

Health checks decide whether a task is safe to receive traffic. A health endpoint should verify that the application process is alive and able to serve basic requests.

GET /health

200 OK
{
  "status": "ok"
}

Important: health checks should be lightweight. Expensive dependency checks can overload a service or create false failures during temporary downstream issues.

Graceful Shutdown

During deployment, ECS stops old tasks. The application should handle termination signals and stop accepting new work while finishing in-flight requests.

Deployment starts
  -> ECS starts new task
  -> New task becomes healthy
  -> ECS drains old task
  -> Old task receives stop signal
  -> Application finishes in-flight work
  -> Old task exits

Production Note: graceful shutdown is especially important for APIs, queue workers, file processing, payment workflows, and any workload with non-idempotent operations.

Common Mistakes

Most mistakes around ECS task definitions, services, and deployments come from treating tasks like permanent servers. ECS tasks are disposable runtime units, and services are responsible for replacing them.

  • Deploying with latest instead of immutable image tags.
  • Forgetting to update the service after pushing a new image.
  • Running only one task and expecting reliable rolling deployments.
  • Using slow or unreliable health checks that break deployment stability.
  • Keeping durable state inside containers.
  • Ignoring graceful shutdown during task replacement.
  • Making database changes that are not backward-compatible.
  • Confusing task definition revision with Docker image version.
  • Setting CPU and memory without measuring runtime behavior.
  • Assuming ECS fixes broken application startup logic.

Production Checklist

A production ECS service should make task replacement predictable. The task definition, service configuration, health checks, deployment settings, and application behavior should work together.

  • Use immutable image tags tied to Git commits or release versions.
  • Register a new task definition revision for each application release.
  • Update the ECS service to deploy the new revision.
  • Run more than one task for production services that require availability.
  • Configure lightweight health checks for load-balanced workloads.
  • Use deployment settings that preserve enough healthy capacity.
  • Keep tasks stateless and store durable data externally.
  • Implement graceful shutdown for APIs and workers.
  • Make database migrations backward-compatible with old and new task versions.
  • Send logs to a centralized destination such as CloudWatch Logs.
  • Measure CPU and memory usage before tuning task size.
  • Automate releases through CI/CD instead of manual service updates.
  • Test rollback behavior before production incidents require it.

Conclusion

ECS task definitions, tasks, services, and deployments form the foundation of how ECS runs production workloads. The task definition describes the runtime, the task is the running copy, the service maintains desired count, and the deployment process replaces old tasks with new ones.

The most important production idea is that ECS tasks are disposable. A healthy ECS architecture expects tasks to be replaced during deployments, failures, scaling events, and infrastructure changes.

Key Takeaway: ECS becomes much easier to understand when task definitions are treated as blueprints, tasks as replaceable runtime units, services as desired-state controllers, and deployments as controlled task replacement.

Continue with ECS articles that go deeper into compute choices, networking, workload patterns, scaling behavior, and production operations.

Comments (0)