There are many ways to protect your EC2 Instances from being exposed to the Internet. One way is to give them private IP addresses and put them behind a public-facing Elastic Loadbalancer. This way your ELB spreads the incoming traffic across your Instances and your EC2 Instances do not have to directly be connected to the Internet.
As simple as it sounds, this design on AWS requires a rather complex network configuration. I have tried to summarize the whole concept in the diagram below. Well, because a picutre always speaks a thousand words. I have also added some brief explanations to help you understand it better.
Before we continue, I highly suggest you read this blog post in which I have briefly explained some VPC concepts: AWS VPC Concepts Simply Explained!
Now let’s get to the business:
- In this design, I have two EC2 Instances and each is in a separate private subnet. We want to allow traffic to these private Instances from the Internet using an ELB and yet again we also need them to be able to send their outgoing traffic to the Internet.
- There needs to be an Internet Gateway attached to the VPC to allow the VPC to communicate to the Internet.
- I have created a separate small public subnet and added a NAT gateway to it. The NAT Gateway helps with moving the outgoing traffic to the Internet. (I could have placed the NAT Gateway in any public subnet but it was my choice to separate it. It is just simpler, I think.)
- I have created a public-facing ELB (Elastic Load Balancer) and behind it there need to be always at least two public subnets, each in a different Availability Zone.
- Both EC2 Instances are added to the target group which is attached to the ELB.
- Take note the two empty public subnets must exist and they must be in the same Availability Zone as their peering private subnet. Otherwise the ELB will not be capable of sending the traffic to the private subnets.
- I have shown with dotted lines the way packets flow in to reach an EC2 Instance, or out to the Internet. 1-One dotted line shows a scenario when users from the Internet want to reach the Instances in the private subnets. In this case the traffic going back from the instance to the user will travel back through the ELB. 2-The other dotted line shows a scenario when Instances in the private subnets need to communicate to the Internet directly. In this case we need the NAT Gateway.