Amazon ECS (Elastic Container Service) now has blue/green deployments built in, working directly with Elastic Load Balancing. You get zero-downtime releases and a fast way back when a release goes wrong, without AWS CodeDeploy: the ECS deployment controller runs the whole switch itself.

At a glance
  • ECS starts the new version (green) next to the current one (blue), then moves traffic over.
  • You need a load balancer, two target groups, a production listener rule and an ECS infrastructure IAM role.
  • On the ECS service you set strategy: "BLUE_GREEN" and a bake time.
  • Blue keeps running during the bake time, so traffic can go straight back to it.

Below we set it up with TypeScript CDK and then follow the traffic through a deployment.

What is blue/green deployment?

Blue/green deployment is a release strategy with two versions of your service:

  • Blue is the current production version.
  • Green is the new version to be deployed.

Instead of updating running tasks in place, ECS deploys the new version alongside the old one and shifts traffic when it is ready. In this post, the traffic goes through an Application Load Balancer, and the ECS service moves its listener-rule weights.

Architecture diagram of an Amazon ECS blue/green deployment: users reach an Application Load Balancer whose listener rule forwards 100% of traffic to the blue target group and 0% to the green target group, while the ECS deployment controller shifts the weights using an infrastructure IAM role.
One ALB, two target groups, one ECS service. The ECS deployment controller moves the listener-rule weights.

Why use blue/green deployments?

With a rolling update, ECS replaces tasks a few at a time. For a while, old and new versions serve users side by side, and if the new version is bad, getting back means another deployment.

Blue/green avoids both. Users only reach green after its health checks pass. During the bake time blue is still running, so a rollback is a change of listener weights, not a redeploy. If you add a test listener, you can also send test traffic to green and check your metrics before any production traffic moves.

In short:

ProblemBlue/green solution
Broken deployments affecting usersTraffic only shifts after validation
Hard-to-revert releasesImmediate traffic rollback
Stateful connection disruptionControlled listener switching
Risky in-place upgradesFully isolated environments

Prerequisites for blue/green deployment in ECS

To use AWS-native blue/green deployments with ECS, you need four things.

1. A load balancer

ECS-native blue/green works with an Application Load Balancer (ALB), a Network Load Balancer (NLB) or ECS Service Connect. This post uses an ALB, where you configure:

  • A production listener
  • A listener rule
  • Two target groups (primary and alternate)

With an NLB there are no listener rules, so ECS switches the listener itself.

2. Two target groups

  • Primary target group (blue)
  • Alternate target group (green)

ECS registers the existing tasks in the blue target group and the new revision’s tasks in the green target group.

3. An IAM role for ECS infrastructure

ECS needs a special infrastructure role so it can modify load balancer rules during a deployment. AWS provides a managed policy for it: AmazonECSInfrastructureRolePolicyForLoadBalancers.

4. The blue/green deployment strategy on the ECS service

In your ECS service:

deploymentConfiguration: {
  strategy: "BLUE_GREEN",
  bakeTimeInMinutes: 5,
  maximumPercent: 200,
  minimumHealthyPercent: 100
}
  • bakeTimeInMinutes: how long blue and green both keep running after production traffic has shifted, before blue is stopped.
  • maximumPercent: 200: lets ECS run a full set of green tasks next to blue.
  • minimumHealthyPercent: 100: keeps blue at full capacity until the switch.

TypeScript CDK example

The snippets below use the low-level Cfn* constructs, which map one-to-one to CloudFormation. config, app and element come from our own stack configuration (prefix, container port, health check settings); replace them with your own values. targetGroup is the service’s existing primary target group.

Step 1: Infrastructure role for blue/green

const ecsBlueGreenRole = new iam.CfnRole(this, `${config.prefix}-ecs-blue-green-role`, {
  roleName: "ecsInfrastructureRoleForLoadBalancers",
  assumeRolePolicyDocument: {
    Version: "2012-10-17",
    Statement: [
      {
        Effect: "Allow",
        Principal: { Service: "ecs.amazonaws.com" },
        Action: "sts:AssumeRole"
      }
    ]
  },
  managedPolicyArns: [
    "arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForLoadBalancers"
  ]
});

Step 2: Create the alternate (green) target group

const alternateTargetGroup = new elbv2.CfnTargetGroup(this, `tg-alt-${element}`, {
  name: `tg-alt-${element}-${app.applicationTypeConfigurations.containerPort}`,
  port: app.applicationTypeConfigurations.containerPort,
  protocol: app.applicationTypeConfigurations.protocol,
  targetType: "ip",
  vpcId: cdk.Fn.importValue("outputVpcId"),

  healthCheckEnabled: true,
  healthCheckPath: app.applicationTypeConfigurations.healthCheckPath,
  healthCheckIntervalSeconds: app.applicationTypeConfigurations.healthCheckIntervalSeconds,
  healthyThresholdCount: app.applicationTypeConfigurations.healthyThresholdCount,
  unhealthyThresholdCount: app.applicationTypeConfigurations.unhealthyThresholdCount
});

Now we have:

  • targetGroup → blue
  • alternateTargetGroup → green

Step 3: Production listener rule with weighted routing

Initially, blue gets 100% of the traffic and green gets 0%.

const listenerRule = new elbv2.CfnListenerRule(this, `blue-green-rule-${element}`, {
  listenerArn: ecsLoadBalancerListener.attrListenerArn,
  priority: 10,
  actions: [
    {
      type: "forward",
      forwardConfig: {
        targetGroups: [
          { targetGroupArn: targetGroup.attrTargetGroupArn, weight: 100 },       // Blue
          { targetGroupArn: alternateTargetGroup.attrTargetGroupArn, weight: 0 } // Green
        ]
      }
    }
  ],
  conditions: [
    {
      field: "path-pattern",
      pathPatternConfig: { values: ["/*"] }
    }
  ]
});

Step 4: ECS service with the BLUE_GREEN strategy

const ecsService = new ecs.CfnService(this, `ecs-service-${element}`, {
  cluster: cdk.Fn.importValue("outputEcsClusterName"),
  desiredCount: app.desiredCount,
  // taskDefinition, launchType and networkConfiguration omitted for brevity

  deploymentConfiguration: {
    strategy: "BLUE_GREEN",
    bakeTimeInMinutes: 5,
    maximumPercent: 200,
    minimumHealthyPercent: 100
  },

  loadBalancers: [
    {
      containerName: element,
      containerPort: app.applicationTypeConfigurations.containerPort,
      targetGroupArn: targetGroup.attrTargetGroupArn,
      advancedConfiguration: {
        alternateTargetGroupArn: alternateTargetGroup.attrTargetGroupArn,
        productionListenerRule: listenerRule.ref,
        roleArn: ecsBlueGreenRole.attrArn
      }
    }
  ]
});

How traffic flows during an ECS blue/green deployment

During a blue/green deployment with Elastic Load Balancing, traffic moves through six stages.

Six stages of an Amazon ECS blue/green deployment: initial state, green deployment, optional test traffic, production traffic shift, bake time and completion, with the blue and green traffic weights at each stage.
The ALB listener-rule weights at each stage of the deployment.

1. Initial state

All production traffic routes to the primary target group (blue).

2. Green deployment

ECS deploys the new tasks, registers them in the alternate target group (green) and waits for the health checks to pass.

3. Optional test traffic

If a test listener is configured, test traffic is routed to green while production users still hit blue.

4. Production traffic shift

ECS updates the ALB listener rule: blue goes to weight 0 and green to weight 100. Traffic now flows entirely to green.

5. Bake time

Both versions keep running so you can monitor logs, validate metrics and make sure there are no hidden failures. The length is set with bakeTimeInMinutes: 5.

6. Completion

After a successful bake time, the blue tasks are terminated and green becomes the new production version.

Automatic rollback

If a rollback is triggered during the deployment or the bake time, ECS moves traffic back to blue and stops the green tasks. Users stay on the version that was already working.

Tip: automatic rollback needs a trigger. Turn on the deployment circuit breaker and/or attach CloudWatch alarms to the service with “Rollback on failures” selected, and use lifecycle hooks (a Lambda function or a pause) to run your own checks at each stage. See the AWS documentation on ECS blue/green deployments.

Other deployment strategies in ECS

Blue/green is one of four deployment strategies you can choose for an ECS service:

  • Rolling update: replaces old tasks with new ones in place.
  • Blue/green: runs blue and green side by side and shifts all traffic at once.
  • Canary: shifts traffic in two stages, first a set percentage for testing, then the remainder.
  • Linear: shifts traffic gradually, by a set percentage at a set time interval.
Four small charts comparing how much production traffic reaches the new version over time for rolling update, blue/green, canary and linear deployments in Amazon ECS.
How much production traffic the new version receives over time, per strategy (illustrative).
Amazon ECS console deployment options with the Blue/green strategy selected, a bake time of 1 minute and traffic shifting set to shift all traffic at once.
Choosing the deployment strategy in the Amazon ECS console.

Example of a successful deployment

Amazon ECS console showing the last deployment: status Success, deployment controller ECS, strategy Blue/green, bake time 1 minute, all traffic shifted at once, duration 10 minutes 29 seconds.
A completed blue/green deployment in the Amazon ECS console.
Amazon ECS service deployment configuration: deployment controller ECS, strategy Blue/green, bake time 1 minute, traffic shifting all at once, with no deployment lifecycle hooks.
The service’s deployment configuration after the change.

Conclusion

If you run production services on ECS behind an ALB, blue/green is worth switching on. The extra setup is a second target group, a listener rule and an IAM role. In return, users never see a mix of old and new tasks, and a bad release goes back by moving traffic instead of redeploying.

Need a hand? Cloutive’s DevOps engineers and Solutions Architect set up deployment pipelines like this for our clients. See our DevOps as a Service or get in touch.