Review load balancer attachment for an ECS service

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

Description

An ECS service that must distribute incoming requests across tasks needs a suitable traffic entry point. Addressing tasks directly without a load balancer can make task replacement and failure harder to handle.

Potential impact

Requests may concentrate on one task or reach terminated tasks, reducing service availability.

Remediation

When needed, specify the target group, container name and port in the service’s LoadBalancers, and configure listeners and health checks. Worker services that do not receive requests may not need a load balancer.

Examples

The excerpts attach port 80 of sample-app to a target group. Match the container name and port in the task definition.

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