Sub topic 13
Connecting an Auto Scaling group to a target group
This chapter assumes you can already create an Application Load Balancer, a target group with a health check, and a launch template. It covers how an Auto Scaling group (ASG) registers the instances it launches with a target group, and how the load balancer's health checks feed back into instance replacement.
What the integration does
An ASG and a target group are separate resources. The target group knows nothing about EC2 capacity. The ASG knows nothing about HTTP routing. Linking them gives you three automatic behaviors:
- A new instance is registered with the target group once it is in service, with no manual
register-targetscall. - A terminating instance is deregistered first, so the load balancer stops sending it new requests.
- If you set the ASG health check type to
ELB, the ASG treats a target the load balancer reports as unhealthy as a failed instance and replaces it.
Creating the ASG with a target group
The target group must use --target-type instance, and its VPC must be the VPC of the subnets you give the ASG. A mismatch causes the create call to fail.
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name web-asg \
--launch-template LaunchTemplateName=web-lt,Version='$Latest' \
--min-size 2 \
--max-size 6 \
--desired-capacity 2 \
--vpc-zone-identifier "subnet-aaaa1111,subnet-bbbb2222" \
--target-group-arns "$TG_ARN" \
--health-check-type ELB \
--health-check-grace-period 300This creates a group of 2 to 6 instances across two subnets. Two settings matter most here: --target-group-arns and --health-check-type ELB.
You can also attach a target group to an existing ASG. The older command is attach-load-balancer-target-groups. The newer attach-traffic-sources call works for ALB, NLB and other traffic sources.
aws autoscaling attach-traffic-sources \
--auto-scaling-group-name web-asg \
--traffic-sources Identifier="$TG_ARN",Type=elbv2Attaching a target group to a running ASG registers the instances that are already in the group.
EC2 health checks versus ELB health checks
By default, an ASG uses only EC2 health checks. It replaces an instance when EC2 reports it as stopped, terminated, or failing system status checks. An instance whose web server has crashed still looks healthy to EC2, so the ASG keeps it.
With --health-check-type ELB, the ASG also considers the target group's result. An instance is replaced if it fails either check. This is almost always what you want for a web tier.
The ELB check applies only to target groups attached to the ASG. If the target group's health check path is wrong (for example /health returns 404), every instance fails, and the ASG will keep replacing them.
Grace period and health check timing
A new instance needs time to boot, run user data, and start the application. The health check grace period tells the ASG to ignore failed health checks for that many seconds after the instance enters service.
Set it longer than the time your application needs to become ready, plus the time the target group needs to mark it healthy. The target group's timing is roughly:
time to healthy = health check interval x healthy threshold countWith an ALB default of 30 seconds and a threshold of 5, that is about 150 seconds after the application starts answering. A grace period shorter than your real startup time causes a replacement loop. The ASG launches an instance, the instance is still starting, the check fails, the ASG terminates it, and the cycle repeats.
Security groups and ports
The load balancer talks to instances over the network, so the instance security group must allow it. The usual pattern is to allow the target port (for example 80) from the load balancer's security group, not from 0.0.0.0/0. If this rule is missing, targets stay in unhealthy with a timeout reason even though the application is fine.
Checking target health
Use describe-target-health to see what the load balancer thinks of each instance. This function lists each target and its state:
import boto3
elbv2 = boto3.client("elbv2")
def print_target_health(target_group_arn):
response = elbv2.describe_target_health(TargetGroupArn=target_group_arn)
for description in response["TargetHealthDescriptions"]:
target = description["Target"]["Id"]
state = description["TargetHealth"]["State"]
print(target, state)The states you will see are:
| State | Meaning |
|---|---|
| `initial` | Registration is in progress or the first checks are running. |
| `healthy` | The target passed the required number of checks and receives traffic. |
| `unhealthy` | The target failed the required number of checks. |
| `draining` | The target is being deregistered and finishes in-flight requests. |
| `unused` | The target is not registered, or its Availability Zone is not enabled for the load balancer. |
The response also includes a Reason field, such as Target.Timeout or Target.ResponseCodeMismatch, which points to the cause.
Scale-in and deregistration
When the ASG scales in, it deregisters the chosen instance from the target group. The target enters draining for the target group's deregistration delay, which is 300 seconds by default. The ASG waits for this before terminating the instance, so in-flight requests can finish.
If your requests are short, lower the delay (for example to 30 seconds) so scale-in and deployments finish faster. If you have long uploads or WebSocket connections, keep it longer or handle reconnects in the client.
Availability Zone balance
The ASG spreads instances evenly across the subnets you list. The load balancer must have those same Availability Zones enabled, or instances in a missing zone show as unused and receive no traffic. Enable the same zones on both sides, and enable cross-zone load balancing where traffic would otherwise skew toward the zone with fewer instances.
Common errors
- Targets stay
initialthenunhealthy: the application is not listening on the target group port, the path returns a non-matching status code, or the security group blocks the load balancer. - Instances are replaced right after launch: the grace period is shorter than startup time.
- A crashed application is never replaced: the health check type is still
EC2. - Create fails with a VPC error: the subnets and the target group are in different VPCs.
Exercise
Your ASG uses health check type EC2. A bug makes the web server on one instance return HTTP 500 on /health, but the instance itself is running. The target group shows it as unhealthy. What happens to it, and what do you change?
Show answer
The ASG does not replace it, because EC2 status checks pass and the ASG ignores the target group result. The load balancer stops sending traffic to it, but it keeps running and costing money, and capacity is reduced. Change the ASG health check type to ELB (for example with update-auto-scaling-group --health-check-type ELB and a grace period longer than startup time), so the ASG terminates and replaces the instance.