Sub topic 11
Running a long-lived service
This chapter assumes you can write a Fargate task definition, you know the awsvpc networking model, and you have an image in ECR. Here you will turn a task definition into a service that keeps a set number of copies running.
Tasks versus services
A task is one running copy of a task definition. If you start it with aws ecs run-task, ECS places it, runs it, and does nothing more. When the container exits or the host fails, the task is gone and nobody replaces it. That fits batch jobs and one-off commands.
A service is a controller that you configure with a task definition and a desired count. ECS keeps comparing the number of running tasks with that count. If a task stops, the service starts a replacement. Web servers, APIs, and queue workers that must always be available should run as services.
The scheduler's reconciliation loop
The service scheduler works as a loop:
- Read the desired count and the task definition.
- Count the tasks that are running or pending.
- If there are too few, place new tasks. If there are too many, stop some.
- Wait, then repeat.
The scheduler also acts when a task fails its health check, when an essential container exits, or when a load balancer marks a target unhealthy. In each case it stops the task and starts a new one.
Creating the service
This command creates a two-task service behind an ALB target group:
aws ecs create-service \
--cluster demo \
--service-name web \
--task-definition web-app \
--desired-count 2 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-aaa111,subnet-bbb222],securityGroups=[sg-0123456789abcdef0],assignPublicIp=DISABLED}" \
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web/0123456789abcdef,containerName=web,containerPort=8080" \
--health-check-grace-period-seconds 60 \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}"Each option has a specific job:
| Option | What it controls |
|---|---|
| `--task-definition web-app` | The blueprint. A family name with no revision resolves to the latest active revision at the moment you run the command. |
| `--desired-count 2` | How many tasks the service tries to keep running. |
| `--launch-type FARGATE` | Runs tasks on Fargate. You can use a capacity provider strategy instead, but not both. |
| `--network-configuration` | The subnets and security groups for each task's network interface. |
| `--load-balancers` | Registers each task's IP address in the target group. |
| `--health-check-grace-period-seconds` | How long the scheduler ignores load balancer health failures after a task starts. |
The service also pins that revision. Registering a new revision of web-app later does not change a running service. You roll it out by calling update-service, which the deployments chapter covers.
How tasks are placed
The Fargate scheduler only supports the replica strategy, which keeps the desired count of tasks. The daemon strategy, which puts one task on every instance, is for EC2 container instances and does not apply to Fargate.
For placement, ECS spreads tasks across the Availability Zones of the subnets you list. With two subnets in two zones and a desired count of two, you normally get one task per zone. This is why you should list subnets in at least two zones. With a single subnet, one zone failure takes the whole service down.
Inspecting service state
Start with describe-services:
aws ecs describe-services \
--cluster demo \
--services web \
--query "services[0].{desired:desiredCount,running:runningCount,pending:pendingCount,events:events[:5].message}"A healthy service shows running equal to desired and pending at zero. The events list is the service's own log. It records messages such as "has reached a steady state", "was unable to place a task", or "has started 1 tasks". Read it before you look anywhere else.
To list the actual tasks and why one stopped:
aws ecs list-tasks --cluster demo --service-name web --desired-status STOPPED
aws ecs describe-tasks \
--cluster demo \
--tasks TASK_ID \
--query "tasks[0].{status:lastStatus,reason:stoppedReason,containers:containers[].{name:name,exit:exitCode,reason:reason}}"Replace TASK_ID with a task ID from the list. Stopped tasks stay visible for about an hour, so check soon after a failure.
Changing the desired count
You can change the count by hand:
aws ecs update-service --cluster demo --service web --desired-count 4If you also configured Application Auto Scaling, it manages DesiredCount within its minimum and maximum. A manual change is then only temporary, and the next scaling action can overwrite it. Set the bounds through the scalable target, not through update-service.
To restart every task without changing anything, such as to pick up a new image behind the same tag:
aws ecs update-service --cluster demo --service web --force-new-deploymentCommon failures
| Symptom in service events | Likely cause |
|---|---|
| Unable to place a task | No valid subnet, a subnet out of free IP addresses, or a Fargate quota reached. |
| `CannotPullContainerError` | No route to ECR, a wrong image URI, or a missing execution role permission. |
| Task stopped: "Essential container in task exited" | The application crashed. Check the exit code and the CloudWatch logs. |
| Tasks repeatedly started and stopped | Health checks fail before the app is ready. Raise the grace period or fix the health endpoint. |
| Service stuck with pending tasks | Waiting on a network interface or image pull. Check the task's stopped reason. |
Deleting a service
A service with a nonzero desired count cannot be deleted normally. Either scale it to zero first, or force it:
aws ecs delete-service --cluster demo --service web --forceDelete the service before you delete the cluster. Otherwise the cluster deletion fails.
Exercise
A service has desired count 3 but shows runningCount 3 only for a few minutes, then drops to 1 and climbs again, repeating. The service events say the load balancer marked targets unhealthy. The application takes about 90 seconds to start. Which setting should you change first, and why?
Show answer
Raise --health-check-grace-period-seconds to above 90 seconds, for example 120 (use aws ecs update-service --health-check-grace-period-seconds 120). With a 60 second grace period the scheduler counts load balancer health failures before the app is ready, kills the tasks, and starts new ones, which also fail the same way. A longer grace period gives each task time to start before failures count.
Exercise
You set --desired-count 6 with update-service, but a minute later the count is back at 4. Auto scaling has min 2 and max 10. What is the likely cause?
Show answer
The target tracking policy adjusted DesiredCount after your change because the metric (for example average CPU) was below the target, so it scaled in. Manual desired-count changes are overwritten by Application Auto Scaling. To hold more capacity, raise the scalable target's minimum capacity, or change the policy's target value.