Sub topic 12
Exposing a service through an Application Load Balancer
This chapter assumes you can read the task definition and create-service command from earlier chapters. It also assumes you know what a VPC, a subnet, and a security group are. Here you will put an Application Load Balancer (ALB) in front of a Fargate service so that clients reach your tasks through one stable address.
Why a load balancer
With awsvpc networking, every task gets its own private IP address. Tasks start, stop, and get replaced during deployments and scaling, so those addresses keep changing. Clients need one stable name, and something has to spread requests across the healthy tasks.
An ALB does both jobs. It works at HTTP level (layer 7), so it can route by host name or path. It also checks each task's health and stops sending traffic to tasks that fail.
The parts of an ALB
Three objects make up the setup:
- Load balancer: the entry point. It has a DNS name, lives in subnets you choose, and has its own security group.
- Listener: waits for connections on a protocol and port, such as HTTP on 80 or HTTPS on 443. Rules on the listener decide where each request goes.
- Target group: a set of destinations plus a health check. For Fargate, the destinations are task IP addresses.
ECS registers and deregisters tasks in the target group for you. You never add task IPs by hand.
Target type must be ip
A target group has a target type: instance, ip, or lambda. Fargate tasks have no EC2 instance that you manage, and each task has its own network interface. You must therefore use ip. If you pick instance, ECS cannot attach the service to the group and create-service fails.
Step 1: security groups
Use two security groups and chain them:
- The ALB security group allows inbound TCP 80 or 443 from the internet (or from your corporate range).
- The task security group allows inbound TCP 8080 only from the ALB security group, not from
0.0.0.0/0.
Referencing a security group as the source means that only the ALB can reach the tasks. It also keeps working when the ALB's IP addresses change.
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 8080 \
--source-group sg-0aaaabbbbccccddddHere sg-0123456789abcdef0 is the task security group and sg-0aaaabbbbccccdddd is the ALB security group. The ALB must also be able to send traffic to the task port. A security group's default outbound rule allows all traffic, so this normally needs no change.
Step 2: target group, load balancer, and listener
Put the ALB in public subnets in at least two Availability Zones. Keep the tasks in private subnets.
aws elbv2 create-target-group \
--name web \
--protocol HTTP \
--port 8080 \
--vpc-id vpc-0abc1234def567890 \
--target-type ip \
--health-check-path /health \
--health-check-interval-seconds 15 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 3 \
--matcher HttpCode=200-299
aws elbv2 create-load-balancer \
--name web-alb \
--type application \
--scheme internet-facing \
--subnets subnet-pub111 subnet-pub222 \
--security-groups sg-0aaaabbbbccccdddd
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/web-alb/0123456789abcdef \
--protocol HTTP \
--port 80 \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web/0123456789abcdefThe --port 8080 on the target group is the default port for registered targets. For Fargate with awsvpc, ECS registers each task using the container port from the service configuration, so the two should match.
In production, add an HTTPS listener on 443 with a certificate from AWS Certificate Manager. Then change the port 80 listener to redirect to HTTPS.
Step 3: attach the service
The --load-balancers option in create-service connects the service to the target group. This is the command from the earlier service chapter, shown again with the load balancer parts highlighted:
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 60Three values must agree with other resources:
| Value | Must match |
|---|---|
| `containerName` | The `name` in the task definition's container definition (`web`) |
| `containerPort` | A `containerPort` in that container's `portMappings` (`8080`) |
| `targetGroupArn` | A target group in the same VPC as the task subnets, with target type `ip` |
The service can attach to a target group only if the load balancer already has a listener that references it. If you create the target group but never add a listener, create-service returns an error.
How registration works
When a task starts, the ECS scheduler registers its private IP and port with the target group. The target then goes through the states initial, then healthy once it passes the required number of checks. A task that fails the health checks becomes unhealthy, and ECS replaces it.
When a task stops, ECS deregisters it. The target enters draining and stays there for the deregistration delay, 300 seconds by default. In-flight requests can finish during this time. For an API with short requests, lowering the delay speeds up deployments:
aws elbv2 modify-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web/0123456789abcdef \
--attributes Key=deregistration_delay.timeout_seconds,Value=30The delay should be longer than your slowest normal request. Otherwise the load balancer cuts off connections that were still working.
Routing more than one service
One ALB can front many services. Add listener rules that match a path or host header and forward to a different target group for each service. For example, /api/* goes to the api target group and everything else goes to web. This is cheaper than running one ALB per service, because an ALB has an hourly charge.
Common errors
- 503 Service Unavailable: the target group has no healthy targets. Check the target health reason in the console or with
aws elbv2 describe-target-health. - 504 Gateway Timeout: the ALB cannot reach the task. The task security group usually does not allow the ALB security group on the container port.
- Targets stay
unhealthy: the health check path returns something outside the matcher (a redirect, 401, or 404), or the app listens only on127.0.0.1instead of0.0.0.0. - Tasks restart in a loop: the ALB marks new tasks unhealthy before the app has started. Set
--health-check-grace-period-secondslong enough for startup. - Cannot create the service: the target group type is
instance, or the container name or port does not match the task definition.
Exercise
Your service is running two tasks, but the ALB returns 504 for every request. The target group shows the targets as unhealthy with the reason "Request timed out". The tasks listen on port 8080. What do you check first, and what is the likely fix?
Show answer
Check the task security group. A timeout means the ALB's health check requests never reach the task. The likely cause is that the task security group has no inbound rule for TCP 8080 from the ALB security group. Add a rule with authorize-security-group-ingress that uses the ALB security group as the source. Also confirm the app listens on 0.0.0.0, not 127.0.0.1.