Compute and load balancing on AWS
Wire an ALB, target group, listener, launch template and Auto Scaling group with security groups that reference each other, and what the ALB costs per month.
Compute and load balancing on AWS
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- The app security group should allow traffic from the ALB's security group, not a CIDR, so the rule survives instances coming and going.
- The ASG registers instances in the target group; health_check_type = ELB makes it replace instances the load balancer marks unhealthy.
- Use launch templates (aws_launch_configuration is discouraged), IMDSv2 via metadata_options, and instance_refresh so template changes roll through the fleet.
- An ALB costs $0.0252 per hour in eu-west-1 on the price list I read, about $18.40 per month before capacity units, so share ALBs across services.
A service that survives its own server
One EC2 instance behind a public IP works until the instance dies, the zone has a bad hour or you need to deploy. Then someone logs in and restarts something by hand. The standard shape that removes that person is three pieces: an Application Load Balancer that terminates traffic and checks health, an Auto Scaling group that keeps N copies of a launch template running across zones, and security groups that say who may talk to whom. This lesson writes that in Terraform on top of the VPC from the last lesson and the role from the one before.
The idea behind each piece is covered in the devops lessons on reverse proxies and load balancers and autoscaling. Here the question is how the Terraform resources fit together, which is where the bugs live.
How the pieces connect
internet -> ALB (public subnets, sg: 80/443 from anywhere)
-> listener -> target group
<- ASG instances (private subnets, sg: 8080 only from ALB's sg)
Four connections to get right:
- The security groups reference each other: the app’s group allows port 8080 from the ALB’s security group, not from a CIDR. When instances come and go, the rule stays valid.
- The listener forwards to a target group, and the target group defines the health check.
- The ASG registers its instances into the target group, and with
health_check_type = "ELB"it replaces instances that the load balancer marks unhealthy, not just ones EC2 says have stopped. - The ASG launches from a launch template, which holds the AMI, instance type, security group, instance profile and user data.
The Terraform
Written from the AWS provider documentation, not run by me, because Terraform and an AWS account are not available here. It assumes the aws_vpc.main and subnets from the previous lesson, plus an aws_iam_instance_profile.app and an AMI data source:
resource "aws_security_group" "alb" {
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_security_group" "app" {
vpc_id = aws_vpc.main.id
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
security_groups = [aws_security_group.alb.id]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_lb" "web" {
load_balancer_type = "application"
subnets = [for s in aws_subnet.public : s.id]
security_groups = [aws_security_group.alb.id]
}
resource "aws_lb_target_group" "web" {
port = 8080
protocol = "HTTP"
vpc_id = aws_vpc.main.id
health_check {
path = "/healthz"
matcher = "200"
}
}
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.web.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.web.arn
}
}
resource "aws_launch_template" "web" {
name_prefix = "web-"
image_id = data.aws_ami.app.id
instance_type = "t4g.small"
vpc_security_group_ids = [aws_security_group.app.id]
iam_instance_profile { name = aws_iam_instance_profile.app.name }
metadata_options { http_tokens = "required" }
user_data = filebase64("${path.module}/boot.sh")
}
resource "aws_autoscaling_group" "web" {
min_size = 2
max_size = 6
vpc_zone_identifier = [for s in aws_subnet.private : s.id]
target_group_arns = [aws_lb_target_group.web.arn]
health_check_type = "ELB"
launch_template {
id = aws_launch_template.web.id
version = aws_launch_template.web.latest_version
}
instance_refresh {
strategy = "Rolling"
preferences { min_healthy_percentage = 90 }
}
}
Things in it that matter. http_tokens = "required" turns on IMDSv2, the token-based version of the instance metadata service; it appears in the launch template docs, and I left it on because instances that can be tricked into fetching the old unauthenticated version leak their role credentials. Pointing the ASG at latest_version plus instance_refresh means a changed template rolls the fleet gradually, instead of only affecting instances launched later. Do not use aws_launch_configuration: the provider’s own docs carry a warning that launch configurations are discouraged in favour of launch templates.
The listener here is HTTP on port 80 to keep the example short. In production you add an aws_lb_listener on 443 with a certificate, and either redirect port 80 to it or leave it closed. The TLS lesson in devops covers certificates.
Where this breaks in practice
- Health check path. The target group probes
/healthzand expects200. If your app returns a redirect or needs auth, every instance is marked unhealthy, the ASG replaces them endlessly and you see a refresh loop. The ASG docs mention that waiting for capacity can time out and mark the group tainted when new instances do not pass the load balancer’s health checks. - Ordering. The ALB must exist before the ASG registers with its target group, and a destroy must reverse it. Terraform’s implicit dependencies through attribute references handle most of this, as the dependency lesson shows. NAT gateways and the internet gateway are the usual places where an explicit
depends_onis needed. - Replace without downtime. Anything that forces a new target group while a listener points at it needs
create_before_destroy, from the lifecycle lesson, and a unique name orname_prefix. - Desired capacity. If you let the autoscaler change the size and Terraform also sets
desired_capacity, every apply fights the scaler. Leave it out, or useignore_changeson it.
What the load balancer costs
I pulled the public AWS Price List for load balancing in eu-west-1, published 25 November 2026. An Application Load Balancer is $0.0252 per hour, plus $0.008 per used load balancer capacity unit per hour. Over a 730-hour month the fixed part is about $18.40 per load balancer, before any traffic. One ALB per service, per environment, adds up, so teams share one ALB across services with host or path rules on listeners. That price is the first thing an Infracost run would show you.
Alternatives, briefly
This lesson uses EC2 behind an ALB. The same ALB resources front containers on ECS or pods on Kubernetes, with the target type changed (ip instead of instance). The ASG part gets replaced by a service definition. The network and role parts stay the same.
About the video
The embed is kodEdge’s “5. Setup AWS Application Load Balancer with Auto Scaling Group using Terraform”, 31 minutes 39 seconds, May 2024. Its chapter list covers the architecture, the VPC recap, creating the security groups, the ALB and the Auto Scaling group, and applying the code, and its description says the ALB is in a public subnet with the Auto Scaling group in a private one, which matches the diagram above. It is the fifth lecture of a series, so it depends on earlier ones. It is a small channel. I did not check whether it uses a launch template or a launch configuration, and the lesson text above is from the provider docs. English was judged from the title, description, channel and its English auto-caption track.
Where this fits
Instances are one way to run an app. The next lesson covers the other big one, a managed Kubernetes cluster, and the two providers that put workloads on it: Kubernetes clusters and the kubernetes and helm providers.
Check yourself
Why reference the ALB security group in the app group's ingress rule?
Instances change, but the ALB's group stays the same, so the rule stays correct without maintaining IP ranges.
What does health_check_type = ELB change for the Auto Scaling group?
It replaces instances that the load balancer reports unhealthy, not only instances that EC2 reports as stopped.
Why leave desired_capacity out when an autoscaler changes the size?
Otherwise each apply resets the size and fights the scaler. Leave it out or ignore changes to it.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.