VPC, EC2, security groups & load balancers
Launch a reachable, locked-down server in your own VPC.
By Invicly Tech, , in Full DevOps with Python. About 13 minutes to read.
In short
A VPC is your private network in AWS. Public subnets face the internet through a load balancer, while servers sit in private subnets reachable only through tightly scoped security groups.
Explained simply
A VPC (Virtual Private Cloud) is your own private network inside AWS. You choose its address range, split it into smaller pieces called subnets, and decide which pieces can talk to the internet. Nothing gets in unless you open a path.
Each subnet lives in one availability zone (AZ), which is one or more separate data centres in a region. Teams build at least two of everything, one per AZ, so a problem in one building does not take the app down.
A public subnet has a route to an internet gateway. A private subnet does not. Your load balancer goes in public subnets, and your servers go in private subnets where nobody on the internet can reach them directly.
EC2 is the service for virtual servers, called instances. You pick an image (AMI) with the operating system, a size (instance type, like t3.micro), a subnet and a security group, which is a firewall that lists the traffic allowed in.
An Application Load Balancer (ALB) gives users one stable address. It receives every request, checks which servers are healthy, and passes the request to one of them. If a server dies, the ALB simply stops sending it traffic.
Press Play on a diagram to walk through it one step at a time.
- 1Internet
Users send HTTPS requests to the load balancer's DNS name.
- 2Internet gateway
Connects the VPC to the internet; public routes point here.
- 3ALB in public subnets
Spread over two availability zones; SG allows 443.
- 4EC2 in private subnets
SG allows app port only from the ALB's security group.
- 5NAT gateway
Lets private instances reach out for updates, not in.
- ALB to EC2 app: Health check GET /health every few seconds1Health check GET /health every few seconds
- EC2 app to ALB: 200 OK, marked healthy2200 OK, marked healthy
- Browser to ALB: HTTPS GET /api/orders on 4433HTTPS GET /api/orders on 443
- ALB to Target group: Rule /api/* picks the api target group4Rule /api/* picks the api target group
- ALB to EC2 app: HTTP to port 8000, X-Forwarded-For added5HTTP to port 8000, X-Forwarded-For added
- EC2 app to ALB: 200 with JSON6200 with JSON
- ALB to Browser: Response over the TLS connection7Response over the TLS connection
In depth
Planning addresses: CIDR blocks and subnets
A VPC gets an IPv4 range written in CIDR notation, such as 10.0.0.0/16. The number after the slash says how many bits are fixed; the rest are free for hosts. A /16 gives 65,536 addresses, a /24 gives 256. AWS allows VPC sizes from /16 down to /28.
Use private ranges (10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16) and pick one that does not overlap your office network or other VPCs, because overlapping ranges cannot be peered or connected later without pain.
AWS reserves 5 addresses in every subnet: the first four and the last one (network address, VPC router, DNS, future use, and broadcast). So a /24 subnet has 251 usable addresses. A common starter layout is a /16 VPC with four /24 subnets: public and private in each of two AZs, leaving plenty of room to add more later.
- AZ a
- Public 10.0.1.0/24: ALB, NAT gateway
- Private 10.0.11.0/24: app servers
- AZ b
- Public 10.0.2.0/24: ALB
- Private 10.0.12.0/24: app servers
- Shared
- Internet gateway
- Public and private route tables
Route tables, internet gateways and NAT
Every subnet is associated with exactly one route table. Each table always has a local route covering the VPC range, so all subnets can reach each other. The table's other routes decide where everything else goes.
The public route table sends 0.0.0.0/0 to the internet gateway (igw-...). An instance there still needs a public IP address to be reachable or to reach out. The private route table sends 0.0.0.0/0 to a NAT gateway that sits in a public subnet. NAT lets private instances start connections out, for package updates or API calls, but never accepts connections started from outside.
NAT gateways are billed per hour and per GB processed, so heavy traffic to S3 through NAT gets expensive. A gateway VPC endpoint for S3 (or DynamoDB) is free and sends that traffic over AWS's network instead. For high availability, run one NAT gateway per AZ and point each private route table at the one in its own AZ.
- 1Instance 10.0.11.25
Opens a connection to pypi.org
- 2Private route table
0.0.0.0/0 points to the NAT gateway
- 3NAT gateway
Swaps the source for its own Elastic IP
- 4Internet gateway
Public subnet route sends it out
- 5Reply returns
NAT maps it back to 10.0.11.25
Security groups and network ACLs
A security group (SG) is attached to a network interface, so it protects each instance, load balancer or database individually. It contains only allow rules, and it is stateful: if a request is allowed in, the reply is allowed out automatically. A new SG allows no inbound traffic and all outbound traffic. A rule's source can be a CIDR range or another security group, which is the cleanest way to say "only the ALB may talk to the app".
A network ACL works at the subnet edge. It is stateless, so you must allow return traffic yourself, usually on ephemeral ports 1024 to 65535. Its numbered rules are checked from the lowest number up, the first match wins, and it supports Deny rules. The default NACL allows everything, and most teams leave it that way and do the real work in security groups, using NACLs only to block a known bad range.
- Attached to an instance or ENI
- Stateful: replies allowed automatically
- Allow rules only
- Can reference another SG
- Attached to a subnet
- Stateless: allow return ports too
- Allow and Deny rules
- Lowest rule number matching wins
Launching and reaching an EC2 instance
An instance needs an AMI, an instance type, a subnet, security groups and, usually, an IAM role. Burstable types like t3 or t4g (ARM, often cheaper) suit small apps; they earn CPU credits while idle and spend them under load.
A key pair is for SSH. AWS keeps the public key and puts it on the instance at first boot; you download the private key once and keep it with chmod 400. The login name depends on the AMI: ec2-user for Amazon Linux, ubuntu for Ubuntu.
In a private subnet you cannot SSH in from home. The modern answer is AWS Systems Manager Session Manager: the SSM agent (preinstalled on Amazon Linux and Ubuntu AMIs) connects outward, so you open a shell with aws ssm start-session and no inbound port at all. The role needs the AmazonSSMManagedInstanceCore policy.
User data is a script that runs as root on first boot, handy for installing packages. Require IMDSv2 on every instance to protect role credentials.
- chmod 400 key.pem, then ssh -i key.pem ec2-user@IP
- aws ssm start-session --target i-0abc... needs no open port
- Use --metadata-options HttpTokens=required to force IMDSv2
How an ALB routes requests
An ALB has listeners, rules and target groups. A listener waits on a port, typically 443 with a certificate from AWS Certificate Manager (ACM), plus port 80 with a rule that redirects to HTTPS. Rules look at the host name or path, such as /api/*, and forward to a target group. A target group is a set of instances, IP addresses or Lambda functions on a given port.
The ALB must have subnets in at least two AZs. It health checks each target on a path you choose, such as /health, and only sends traffic to healthy ones. When a target is deregistered, the ALB stops new requests but waits for the deregistration delay (300 seconds by default) so running requests can finish.
The ALB ends the client's connection and opens its own to the target, so the app sees the ALB's IP. The real client IP arrives in the X-Forwarded-For header. An Auto Scaling group can register new instances in the target group automatically.
- Health check path should be cheap and not depend on slow downstream calls
- Target.Timeout in target health usually means a security group or listen address problem
- Point your domain at the ALB with a Route 53 alias record
Learn it in 5 short steps
About 1h 10m each. Track them with a timer in your plan.
- 1Build a VPC with public and private subnets~1h 10m
- 2Configure route tables and gateways~1h 10m
- 3Launch EC2 with a key pair~1h 10m
- 4Lock down security groups~1h 10m
- 5Put an ALB in front of instances~1h 10m
Key points
- A subnet is public only if its route table sends 0.0.0.0/0 to an internet gateway.
- Security groups are stateful allow lists; reply traffic is allowed automatically.
- Reference the ALB's security group instead of opening app ports to 0.0.0.0/0.
- Use key pairs or Session Manager for access, and never open SSH to the world.
Key terms
Tap a card to flip it. 0/5 known
Examples
aws ec2 authorize-security-group-ingress --group-id sg-app123 --protocol tcp --port 8000 --source-group sg-alb456
aws ec2 run-instances --image-id ami-0abc123 --instance-type t3.micro --subnet-id subnet-priv1 --security-group-ids sg-app123 --key-name deploy-key
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/api/abcAllow traffic only from the ALB, launch privately, check target health.
Build the network skeleton with the CLI
Step 1: create the VPC and keep its ID. Step 2: create a public subnet in one AZ. Step 3: create an internet gateway and attach it to the VPC. Step 4: create a route table with a default route to the gateway. Step 5: associate it with the subnet, which is the moment the subnet becomes public. Repeat steps 2 and 5 for a second AZ, and build private subnets with their own route table pointing at a NAT gateway. In real projects you would write this in Terraform, but doing it once by hand shows what each piece is.
VPC=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query Vpc.VpcId --output text)
PUB=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.1.0/24 \
--availability-zone us-east-1a --query Subnet.SubnetId --output text)
IGW=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)
aws ec2 attach-internet-gateway --internet-gateway-id $IGW --vpc-id $VPC
RT=$(aws ec2 create-route-table --vpc-id $VPC --query RouteTable.RouteTableId --output text)
aws ec2 create-route --route-table-id $RT --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW
aws ec2 associate-route-table --route-table-id $RT --subnet-id $PUB
aws ec2 modify-subnet-attribute --subnet-id $PUB --map-public-ip-on-launchDebug unhealthy targets behind the ALB
Users get errors and the target group shows instances as unhealthy. Step 1: read the reason code with describe-target-health. Step 2: Target.Timeout means the ALB could not connect: check that the app SG allows the app port from the ALB's SG, and that the app listens on 0.0.0.0, not 127.0.0.1. Step 3: Target.ResponseCodeMismatch means it connected but the health path returned, for example, 404 or 500: check the path and the success codes. Step 4: test from inside the instance with curl. Step 5: fix, then watch the state change to healthy after the healthy threshold is met.
aws elbv2 describe-target-health --target-group-arn $TG \
--query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State,TargetHealth.Reason]'
aws ec2 describe-security-groups --group-ids sg-app123 \
--query 'SecurityGroups[0].IpPermissions'
# on the instance (via Session Manager):
ss -ltnp | grep 8000 # 127.0.0.1:8000 means only local; use --host 0.0.0.0
curl -i http://localhost:8000/healthQuick reference
- A subnet is public only when its route table sends 0.0.0.0/0 to an internet gateway
- AWS reserves 5 IPs per subnet, so a /24 has 251 usable addresses
- Private subnets reach out through a NAT gateway; one per AZ for high availability
- Use a free S3 gateway endpoint to avoid NAT data charges for S3 traffic
- Security groups are stateful allow lists; NACLs are stateless with numbered allow and deny rules
- Allow the app port from the ALB's security group ID, not from 0.0.0.0/0
- aws ssm start-session --target INSTANCE_ID gives a shell with no SSH port open
- The ALB needs subnets in at least two AZs; the client IP is in X-Forwarded-For
Common mistakes
- Opening port 22 to 0.0.0.0/0 to make SSH work.
- Placing the ALB in only one availability zone, which AWS does not allow anyway.
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 every subnet in a VPC with its CIDR, AZ and whether instances get a public IP by default.
- Exercise 2medium
Create an app security group that accepts port 8000 only from the ALB's security group, then launch a t3.micro into a private subnet with it, IMDSv2 required and no public IP.
- Exercise 3hard
Put an ALB in front of the instance: target group with a /health check, register the instance, and an HTTP listener on port 80. Then check target health.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a public and a private subnet?
- Nothing about the subnet itself: it is only the route table. A public subnet routes 0.0.0.0/0 to an internet gateway, and a private one does not (it may route to a NAT gateway for outbound access).
- Do I need a NAT gateway?
- Only if instances in private subnets must reach the internet, for updates or external APIs. It costs money every hour, so for S3 and DynamoDB use free gateway endpoints, and for other AWS services consider interface endpoints.
- ALB or NLB: which load balancer should I use?
- Use an ALB for HTTP and HTTPS apps: it understands paths, hosts and headers. Use a Network Load Balancer for raw TCP or UDP, very high throughput, or when you need static IP addresses.
- Why can't I SSH into my instance?
- Check in order: the instance has a public IP or you are on a path into the VPC, the route table, the security group allows port 22 from your IP, the right key and user name. For private instances, use Session Manager instead.