Review load balancer attachment for an ECS service

Attach a load balancer to ECS services that need request distribution.

Description

If an ECS service distributes incoming requests, provide an entry point that stays valid when tasks are replaced. Workers that receive no requests may not need a load balancer.

Potential impact

Clients using individual task addresses can send traffic to a terminated task or overload a single one.

Remediation

For a load-balanced service, set LoadBalancers to the target group and the container name and port from the task definition. Configure the listener and health checks, then verify that new tasks register as healthy.

Examples

The second excerpt attaches sample-app on port 80 to TargetGroup. Both excerpts request two tasks.

Before

yaml
Resources:
  ECSService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: !Ref ECSCluster
      TaskDefinition: !Ref ECSTaskDefinition
      DesiredCount: 2

After

yaml
Resources:
  ECSService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: !Ref ECSCluster
      TaskDefinition: !Ref ECSTaskDefinition
      DesiredCount: 2
      LoadBalancers:
        - TargetGroupArn: !Ref TargetGroup
          ContainerName: sample-app
          ContainerPort: 80

References