5 min read

AWS in Practice - Launching EC2 Instances and a Target Group from Scratch

1. A New Series: Load Balancing on AWS

Putting an application into production almost never means “one machine running the code”. It means several identical instances, traffic distributed across them, automatic replacement of whatever fails and, increasingly, routing decisions that happen before traffic even reaches a load balancer — in DNS itself. In this new two-article series, we’ll build that scenario on AWS: first, launching EC2 instances and organizing them into a target group; then, in the next article, looking at Route 53 and how load balancing also happens at the name resolution layer.

We start with the foundation: what an EC2 instance is, how to create a few of them repeatably, and how to group them so a load balancer (or another consumer) knows where to send traffic.

2. What EC2 Is

Amazon EC2 (Elastic Compute Cloud) is AWS’s virtual machine service. Each instance runs on a type (t3.micro, m5.large, etc.) that defines CPU, memory and network characteristics, from an AMI (Amazon Machine Image) — a disk image with the operating system and, optionally, software already installed. The elements that matter most when planning a fleet of instances behind a load balancer are:

  • Subnet: which subnet (and therefore which availability zone) the instance is launched in. Spreading instances across subnets in different AZs is what ensures a data center outage doesn’t take the application down.
  • Security Group: the instance’s firewall, controlling inbound and outbound ports.
  • Key pair: the key pair used for initial SSH access.
  • User data: a script run on first boot, useful for installing and starting the application without depending on a custom AMI.

3. Creating an EC2 Instance via the CLI

To keep things reproducible, the examples below use the AWS CLI. First, a security group allowing HTTP and SSH:

aws ec2 create-security-group \
  --group-name web-servers-sg \
  --description "SG for web instances behind the target group" \
  --vpc-id vpc-0123456789abcdef0

aws ec2 authorize-security-group-ingress \
  --group-id sg-0123456789abcdef0 \
  --protocol tcp --port 80 --cidr 0.0.0.0/0

aws ec2 authorize-security-group-ingress \
  --group-id sg-0123456789abcdef0 \
  --protocol tcp --port 22 --cidr 10.0.0.0/16

With the security group ready, launch the instance with user data that installs and starts a minimal web server:

aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t3.micro \
  --key-name my-key \
  --security-group-ids sg-0123456789abcdef0 \
  --subnet-id subnet-0aaa111122223333 \
  --count 1 \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-01}]' \
  --user-data '#!/bin/bash
yum install -y nginx
systemctl enable nginx
systemctl start nginx'

Repeating the command with a different subnet-id (a subnet in another AZ) and Name tag creates a second instance that’s identical in terms of application, but physically isolated from the first — the starting point for high availability.

4. The Same Scenario in Terraform

Running run-instances by hand neither scales nor is repeatable. In a real project, the same scenario is usually described in Terraform, using count to generate N instances spread across different subnets:

variable "subnet_ids" {
  default = ["subnet-0aaa111122223333", "subnet-0bbb444455556666"]
}

resource "aws_instance" "web" {
  count                  = length(var.subnet_ids)
  ami                    = "ami-0abcdef1234567890"
  instance_type          = "t3.micro"
  subnet_id              = var.subnet_ids[count.index]
  vpc_security_group_ids = [aws_security_group.web.id]
  key_name               = "my-key"

  user_data = <<-EOF
    #!/bin/bash
    yum install -y nginx
    systemctl enable nginx
    systemctl start nginx
  EOF

  tags = {
    Name = "web-${count.index + 1}"
  }
}

5. Creating the Target Group

A target group is the list of destinations (EC2 instances, IPs or Lambda functions) an AWS load balancer (ALB or NLB) forwards traffic to, along with the health check configuration that decides whether each destination is healthy enough to receive requests:

aws elbv2 create-target-group \
  --name web-servers-tg \
  --protocol HTTP \
  --port 80 \
  --vpc-id vpc-0123456789abcdef0 \
  --health-check-protocol HTTP \
  --health-check-path /healthz \
  --health-check-interval-seconds 15 \
  --healthy-threshold-count 2 \
  --unhealthy-threshold-count 3

The command returns a TargetGroupArn, used both to register instances and, in the next article, to attach the target group to a load balancer listener.

6. Registering the Instances in the Target Group

With the instances up and the target group created, the final step is to register each instance as a target:

aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-servers-tg/abcdef1234567890 \
  --targets Id=i-0123456789abcdef0 Id=i-0fedcba9876543210

From then on, the target group itself monitors each instance’s health through the health check configured in the previous step:

aws elbv2 describe-target-health \
  --target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-servers-tg/abcdef1234567890

The output shows the state (healthy, unhealthy, initial) of each registered instance — this is the state an Application Load Balancer uses to decide whether or not to route traffic to a specific target.

7. Why This Matters Before Talking About Load Balancers

It’s worth noting that, so far, no load balancer has been created — only the infrastructure it will consume. This separation is deliberate: a target group exists independently of the listener/load balancer that uses it, which lets you change routing strategy (a classic ALB, path-based rules, or the DNS-based routing we’ll see next) without recreating the instances or the way they’re grouped.

8. Conclusion

EC2 instances spread across multiple availability zones and grouped into a target group with an active health check are the foundation of any high-availability architecture on AWS — it’s this grouping that any load balancer, from the classic ALB to more advanced strategies, will consult to know who is able to receive traffic. In the next article of this series, we’ll step out of the traditional load balancer layer and look at Route 53: how DNS itself can distribute traffic across regions and endpoints, with weighted, latency-based and automatic failover routing policies.


References:

  1. Amazon EC2 — User Guide
  2. Elastic Load Balancing — Target Groups
  3. Terraform Provider: AWS — aws_instance