Lesson 3 of 3 Amazon ECS, ECR and Fargate

Deploying New Versions to Amazon ECS Services Safely

This lesson explains how a new version reaches an Amazon ECS service: task definition revisions, rolling update settings, automatic rollback, and the built-in blue/green, linear and canary strategies.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the task definition settings that matter for Fargate deployments.
  • Calculate the effect of minimumHealthyPercent and maximumPercent on a rolling update.
  • Explain how the deployment circuit breaker and deployment alarms roll back a release.
  • Choose between rolling, blue/green, linear and canary deployments.

Task definitions for deployment

A task definition is registered as a numbered revision of a family, such as orders-api:8. For Fargate it sets requiresCompatibilities to FARGATE, uses the awsvpc network mode and defines CPU and memory at task level from the supported combinations. The following excerpt shows the settings that matter most for deployments.

{
  "family": "orders-api",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "512",
  "memory": "1024",
  "runtimePlatform": {"cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX"},
  "executionRoleArn": "arn:aws:iam::111122223333:role/ordersTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::111122223333:role/ordersTaskRole",
  "containerDefinitions": [{
    "name": "orders-api",
    "image": "111122223333.dkr.ecr.eu-west-1.amazonaws.com/orders-api:3f9c2ab",
    "portMappings": [{"containerPort": 8080}],
    "secrets": [{"name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:eu-west-1:111122223333:secret:orders/db"}],
    "logConfiguration": {"logDriver": "awslogs", "options": {
      "awslogs-group": "/ecs/orders-api", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "api"}},
    "healthCheck": {"command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
                    "interval": 30, "retries": 3, "startPeriod": 30}
  }]
}

The image is referenced by an immutable tag. The execution role lets ECS pull the image, fetch the secret and send logs, while the task role gives the application its own permissions. A new release is deployed with aws ecs register-task-definition followed by aws ecs update-service --task-definition orders-api:8, or by the ECS deploy action in CodePipeline, which does both from imagedefinitions.json.

Rolling updates

The default deployment type replaces running tasks with tasks of the new revision. Two settings in the service's deployment configuration decide how many tasks run during the update. minimumHealthyPercent is the lower limit of running, healthy tasks as a percentage of the desired count, and maximumPercent is the upper limit of running tasks, old and new together. The following table shows their effect on a service with four desired tasks.

minimumHealthyPercent / maximumPercentDuring the updateTrade-off
100 / 200All four old tasks keep running while up to four new tasks startNo loss of capacity; needs room for double the tasks
50 / 100Two old tasks stop before two new tasks start, then the restNo extra capacity needed; half the capacity during the update
100 / 150Two new tasks start alongside the four old ones at a timeNo capacity loss and only 50% extra, but a slower rollout

A new task counts as healthy only after its container health check and, behind a load balancer, the target group health check pass. The service's health check grace period stops slow-starting tasks from being killed before they are ready.

Fill in the value

Rolling update limits

Exam skills 3.3.6 · 3.3.2

Work out how many tasks run during a rolling update.

Log in to try this activity Interactive activities are free with an account.

Automatic rollback

A deployment whose new tasks crash or fail health checks would otherwise keep retrying. The deployment circuit breaker watches the new tasks; when they repeatedly fail to reach a steady state, it marks the deployment as failed and, with rollback enabled, returns the service to the last completed deployment. Deployment alarms add CloudWatch alarms, such as a high 5xx rate, so a version that starts but misbehaves is also rolled back.

aws ecs update-service --cluster prod --service orders-api --task-definition orders-api:8 \
  --deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}"
Scenario questions

Deploy ECS services safely

Exam skills 3.3.7 · 3.3.6

Practise rollback and safe deployment options for ECS services.

Log in to try this activity Interactive activities are free with an account.

Blue/green, linear and canary deployments

Amazon ECS also has built-in strategies that run the new revision alongside the old one behind a load balancer and shift production traffic to it. With blue/green, the new (green) tasks are started and can be tested on a separate test listener before all traffic moves at once. Linear deployments shift traffic in equal steps, and canary deployments shift a small percentage first and the rest after a wait.

Each strategy has a bake time during which the old tasks are kept so that rollback is immediate, CloudWatch alarms that trigger rollback, and lifecycle hooks that invoke Lambda functions at set stages, for example to run tests before production traffic moves. CodeDeploy blue/green deployments for ECS remain available, but the built-in strategies need no separate CodeDeploy application. The following comparison summarises the choice.

Rolling update
TrafficMoves as tasks are replaced
Extra capacityUp to maximumPercent
RollbackCircuit breaker redeploys the old revision
Choose when Simple releases with little extra capacity.
Blue/green
TrafficMoves all at once after testing
Extra capacityA full second set of tasks
RollbackImmediate during the bake time
Choose when Test the new version before any user sees it.
Linear or canary
TrafficMoves gradually in steps
Extra capacityA full second set of tasks
RollbackImmediate during the bake time
Choose when Expose the new version to users gradually.

For teams that want a running service quickly, Amazon ECS Express Mode creates the service, an Application Load Balancer, scaling and an HTTPS URL from a container image, and all the resources it creates remain visible and editable in the account.

The following diagram shows a blue/green deployment of an ECS service behind a load balancer.

A blue/green deployment of an ECS service. Production traffic reaches the blue tasks running revision 7 while the green tasks running revision 8 are tested through a separate test listener by a lifecycle hook. Traffic then shifts to green all at once, linearly or as a canary, and the blue tasks are kept for a bake time so that a CloudWatch alarm can roll back immediately.
Because the blue tasks keep running during the bake time, a rollback only moves traffic back.
Worked example

A deployment that never finishes

After an update, an ECS service shows its new tasks starting and stopping repeatedly, and the deployment never completes.

The developer runs aws ecs describe-tasks on a stopped task. Its stoppedReason is ResourceInitializationError: unable to pull secrets, and the new revision references a new secret.

The task execution role allows secretsmanager:GetSecretValue only on the old secret. The developer adds the new secret's ARN to the execution role, not the task role, because ECS fetches secrets before the container starts. To stop such loops in future, the developer enables the deployment circuit breaker with rollback, so a failing revision is rolled back automatically.

Check yourself

A service has six desired tasks with minimumHealthyPercent 50 and maximumPercent 100. How many tasks run at the lowest point of a rolling update?

Show answer

Three: ECS may stop up to half of the six tasks before starting new ones, because it may not exceed six running tasks in total.

Exam Tips

Remember for the exam

  • No capacity loss during a rolling update: minimumHealthyPercent 100 and maximumPercent 200.
  • Roll back failing ECS deployments automatically: the deployment circuit breaker with rollback, plus deployment alarms.
  • Test a new version before it receives traffic: an ECS blue/green deployment with a test listener and lifecycle hooks.
  • Unable to pull the image or secrets: fix the task execution role (and the network path to ECR).
  • Read stoppedReason with describe-tasks to find why tasks stop.