Run a self-healing EC2 fleet behind a load balancer
Launch instances from a template into an Auto Scaling group behind an ALB and reach them through Session Manager instead of SSH.
By Invicly Tech, , in AWS Cloud Engineering. About 12 minutes to read.
In short
An EC2 fleet is a group of identical virtual machines that an Auto Scaling group keeps at the size you ask for. A launch template says how to build each instance (AMI, instance type, disk, role, security group, start-up script), and an Application Load Balancer sends traffic only to instances that pass its health check. Add Session Manager for shell access and you get servers that replace themselves when they fail and never need an open SSH port.
Think of it like this: The launch template is a recipe, the Auto Scaling group is a kitchen manager who keeps exactly the right number of dishes on the counter, and the load balancer is the waiter who only serves the dishes that pass inspection.
Explained simply
EC2 gives you virtual servers, called instances. Running one instance by hand is easy, but one instance is fragile. If it crashes, your service is down until someone notices. A fleet fixes that: several identical instances, built the same way, that AWS replaces automatically when one fails.
Three pieces make the fleet. A launch template is the recipe: which image to boot, how big the server is, which disk, which security group and which start-up script. An Auto Scaling group uses that recipe to keep a set number of instances running across two or more Availability Zones. An Application Load Balancer sends user traffic only to instances that answer its health check.
The image is called an AMI, an Amazon Machine Image. It holds the operating system and anything you baked in. The disk is an EBS volume, a network-attached drive. Because instances can be replaced at any time, never keep the only copy of important data on them.
To log in, skip SSH. Session Manager, part of AWS Systems Manager, opens a shell through an agent on the instance. You sign in with IAM, every session can be logged, and the security group needs no inbound port at all. That is safer and easier than managing SSH keys.
Press Play on a diagram to walk through it one step at a time.
- 1ALB health check fails
GET /health returns errors or times out
- 2Target marked unhealthy
ALB stops sending it traffic
- 3ASG sees ELB health status
Health check type is ELB
- 4Instance terminated
Replaced from the launch template
- 5New instance passes checks
After the grace period, back in service
- Back to step 1
- 1User data
Start-up script that installs and starts the app
- 2Instance profile
IAM role for the app and for Session Manager
- 3Network settings
Security group; subnets come from the ASG
- 4EBS volumes
Root volume type and size, encryption
- 5AMI and instance type
The base image and the hardware size
- 1Build new AMI
Patched OS plus app version 1.4
- 2New template version
Points at the new AMI
- 3Start instance refresh
Minimum healthy 90 percent
- 4Replace in batches
Wait for health checks each batch
- 5Verify or roll back
Cancel and refresh to the old version if errors rise
In depth
Launch templates and AMIs
A launch template stores launch settings as numbered versions. You can mark one version as the default, and the Auto Scaling group can point at a specific version, the default, or the latest. Changing a template creates a new version; it does not touch running instances.
For the AMI, start from an AWS-maintained image such as Amazon Linux 2023. Rather than copy an AMI ID, which differs by Region and changes with every update, resolve it from the public Systems Manager parameter, for example /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64. There are two ways to install your app: bake it into a custom AMI (faster boot, more build work) or install it in user data at boot (simpler, slower start). Many teams bake the slow parts and keep only configuration in user data. Require IMDSv2 in the template's metadata options so only token-based instance metadata requests work.
- Template versions are immutable; create a new one to change settings
- Resolve AMI IDs through SSM public parameters
- Bake slow installs; keep user data short
- Require IMDSv2 tokens
EBS volumes: type, size and lifetime
Most root volumes today use gp3, the general-purpose SSD type. It gives a baseline of 3,000 IOPS and 125 MiB/s whatever the size, and you can raise either separately for extra cost. Encrypt volumes; you can turn on EBS encryption by default for the whole Region in account settings.
By default the root volume is deleted when the instance terminates. That is what you want in a fleet, because state should not live there. If an app writes data you care about, put it in S3 or a database, or use EBS snapshots for recovery. Watch for orphaned volumes: extra volumes created with DeleteOnTermination set to false stay behind after an instance dies and keep billing every month.
- gp3 baseline: 3,000 IOPS and 125 MiB/s
- Turn on encryption by default per Region
- Root volume is deleted on terminate by default
- Search for available (unattached) volumes during cleanup
Auto Scaling groups and ALB health checks
An Auto Scaling group has a minimum, a maximum and a desired capacity, and a list of subnets across zones. It balances instances across those zones. With health check type EC2, it only replaces instances whose VM status checks fail. With type ELB, it also replaces instances the load balancer marks unhealthy, which catches a crashed app on a healthy VM.
The target group defines the health check: protocol, path such as /health, the healthy and unhealthy thresholds and the interval. Make the health path cheap and honest: it should fail when the app cannot serve requests, but not when a downstream dependency has a short blip, or one slow database can make the whole fleet look dead. Set the grace period longer than your real boot time. Add a target tracking policy, for example keep average CPU at 50 percent, so capacity follows load.
- ALB target group to Auto Scaling group: i-0aaa unhealthy: 3 failed /health checks1i-0aaa unhealthy: 3 failed /health checks
- Auto Scaling group to EC2: Terminate i-0aaa2Terminate i-0aaa
- Auto Scaling group to EC2: Launch from template version 43Launch from template version 4
- EC2 to New instance: Boot AMI, run user data4Boot AMI, run user data
- New instance to ALB target group: Registered; passes checks after grace period5Registered; passes checks after grace period
Session Manager instead of SSH
Session Manager needs three things. First, the SSM Agent, which comes preinstalled on Amazon Linux 2023 and many other AWS-provided AMIs. Second, an instance profile whose role includes the AWS managed policy AmazonSSMManagedInstanceCore. Third, outbound HTTPS from the instance to Systems Manager, either through NAT or through interface endpoints for ssm, ssmmessages and ec2messages.
On your laptop, install the Session Manager plugin for the AWS CLI. Then aws ssm start-session --target i-0123example opens a shell. Access is controlled with IAM, so you can let developers start sessions only on instances with a given tag. Session activity can be logged to CloudWatch Logs or S3, and port forwarding lets you reach a private database from your laptop without a bastion host.
- Managed policy: AmazonSSMManagedInstanceCore
- Endpoints: ssm, ssmmessages, ec2messages
- No inbound security group rule needed
- Port forwarding replaces bastion hosts
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Write a launch template~40m
- 2Choose an AMI and EBS volume~40m
- 3Create an Auto Scaling group~40m
- 4Use ALB health checks~40m
- 5Connect with Session Manager~40m
Key points
- Launch templates are versioned; the ASG can follow the latest or default version.
- Set the ASG health check type to ELB so it replaces instances the load balancer marks unhealthy.
- Spread the ASG over private subnets in at least two Availability Zones.
- Session Manager gives a logged shell through IAM, with no SSH keys and no inbound ports.
- Treat instances as disposable: keep state in S3, EBS snapshots or a database, never only on one box.
Key terms
Tap a card to flip it. 0/6 known
Examples
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name files-web \
--launch-template LaunchTemplateName=files-web,Version='$Latest' \
--min-size 2 --max-size 4 --desired-capacity 2 \
--vpc-zone-identifier "subnet-0appaexample,subnet-0appbexample" \
--target-group-arns arn:aws:elasticloadbalancing:eu-west-1:111122223333:targetgroup/files-web/0123456789abcdef \
--health-check-type ELB --health-check-grace-period 120Replace the placeholder subnet IDs (comma separated, no spaces) and target group ARN with your own.
Lab: a two-instance fleet behind an ALB
Prerequisites: the VPC from the networking module with public and private subnets in two zones, an ALB in the public subnets with a target group on port 80 and health path /health, and a budget alert. Cost: two t3.micro or t4g.micro instances, the ALB and any NAT gateway bill by the hour; Free Tier may cover part of the instances. Step 1: create a launch template with user data that installs a web server. Step 2: create the ASG with health type ELB (see the explainer example). Evidence: the target group shows two healthy targets and curl to the ALB DNS name returns the page. Cleanup: set desired to 0, delete the ASG, ALB, target group and template.
AMI=$(aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
--query Parameter.Value --output text)
cat > ud.sh <<'EOF'
#!/bin/bash
dnf install -y nginx && echo ok > /usr/share/nginx/html/health && systemctl enable --now nginx
EOF
aws ec2 create-launch-template --launch-template-name files-web --launch-template-data \
"{\"ImageId\":\"$AMI\",\"InstanceType\":\"t3.micro\",\"SecurityGroupIds\":[\"sg-0webexample\"],
\"IamInstanceProfile\":{\"Name\":\"files-web-ssm\"},\"MetadataOptions\":{\"HttpTokens\":\"required\"},
\"UserData\":\"$(base64 -w0 ud.sh)\"}"Proving self-healing and reaching a private instance
Step 1: open a shell with Session Manager on one instance. Evidence: a prompt appears even though the security group has no port 22 rule. Step 2: stop nginx in that shell to simulate an app crash. Step 3: watch the target group mark the instance unhealthy, then the ASG activity history show a termination and a new launch. Evidence: a new instance ID appears and the target group returns to two healthy targets. Rollback is automatic; if the new instance also fails, check user data output in /var/log/cloud-init-output.log.
aws ssm start-session --target i-0123456789abcdef0
# inside the session:
sudo systemctl stop nginx
# back on your laptop:
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:eu-west-1:111122223333:targetgroup/files-web/0123456789abcdef \
--query "TargetHealthDescriptions[].[Target.Id,TargetHealth.State]"
aws autoscaling describe-scaling-activities --auto-scaling-group-name files-web --max-items 3Quick reference
- Launch template = versioned recipe; ASG = keeps N instances; ALB = sends traffic to healthy ones
- Set ASG health check type ELB and a grace period longer than boot time
- Get the latest Amazon Linux AMI from SSM parameter /aws/service/ami-amazon-linux-latest/...
- gp3: 3,000 IOPS and 125 MiB/s baseline; encrypt by default
- Session Manager: SSM Agent + AmazonSSMManagedInstanceCore + outbound 443
- aws ssm start-session --target i-... opens a shell with no SSH
- Use instance refresh to roll a new AMI through the fleet
Common mistakes
- Leaving the health check type as EC2, so instances with a crashed app keep running because the VM itself is fine.
- A grace period shorter than the boot time, so new instances are killed before the app starts and the fleet loops.
- Hard-coding a Region-specific AMI ID in scripts and wondering why it fails in another Region.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List the settings you would put in a launch template for a web server and which ones the Auto Scaling group supplies instead.
- Exercise 2medium
An instance in a private subnet with no NAT does not appear in Fleet Manager and start-session fails. List what to check.
- Exercise 3hard
Plan a zero-downtime rollout of a new AMI to a 4-instance fleet, with automatic rollback if the error rate rises.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is EC2 still worth learning when containers and Lambda exist?
- Yes. Containers on ECS with EC2 capacity, EKS nodes and many legacy apps all run on EC2, and the same ideas (images, health checks, scaling groups) appear on every platform.
- Do I need a bastion host?
- Usually not. Session Manager gives shell access and port forwarding through IAM without a public instance or open SSH port.
- How do I keep a lab within the Free Tier?
- Use a small Free Tier eligible instance type, one or two instances, and delete the ALB and any NAT gateway when you finish, because those bill hourly. Check the current Free Tier terms for your account.