In this recipe, you'll learn how to create a NAT instance on EC2 instances created in a public subnet. The private subnet does not have any Internet Gateway attached to it, so EC2 on private subnet cannot directly communicate with the outside world.
Creating NAT on EC2 instance
Getting ready
We need an AWS account and user with proper permissions for creating a NAT instance on EC2. Create an EC2 in the same way as the previous recipe. The only difference is, you don't put any Advanced Details in the Choose Network page. In the security group page, create NATSG security group and attach the same with instance with the following rules. We are allowing all traffic for simplicity. However, you should only put the required CIDR ranges.
NATSG: Rules
Inbound |
|||
Type |
Protocol |
Port range |
Source |
HTTP |
TCP |
80 |
0.0.0.0/0 and ::/0 |
HTTPS |
TCP |
443 |
0.0.0.0/0 and ::/0 |
SSL |
TCP |
22 |
0.0.0.0/0 and ::/0 |
Outbound |
|||
Destination |
Protocol |
Port range |
Comments |
All traffic |
TCP |
ALL |
0.0.0.0/0 and ::/0 |
You can use the same key pair created before for this instance as well. In the Add tag page, put Nat Instance in value for Name and Key. We also need to create an Elastic IP for attaching it to a NAT instance. This we shall show in the recipe.
How to do it...
- I have created one more EC2 instance as visible in the Instances section of the EC2 console.
- Click on Elastic IPs in the left menu bar.
- Click on Allocate new address.
- Click on Allocate.
- Click on Close. The Elastic IP page will be visible. Choose Elastic IP and click on Actions | Associate address.
- Choose Instance in the Resource type. Select Nat Instance from the Instance drop-down menu. Click on Associate. A success message is shown.
- Go to the Instances menu. You can see that the public DNS and IPv4 public IP has changed. You can see Change Source/Dest. Check is true for the instance.
- Select Actions | Networking | Change Source/Dest. Check.
- You can see that Change Source/Dest. Check is now false.
- We need to update the main Route Table attached to the VPC. Let's go back to the VPC dashboard and select our VPC.
- Click on the Route Tables starting with rtb.
- Select the Route Table and navigate to the Routes tab. Click on the Edit button. Add 0.0.0.0/0 in the destination and the NAT instance ID in Target. Click Save.
How it works...
By default, EC2 instance can either be a source or destination for network traffic request or response. However, NAT instances need to forward requests to the internet that were originated from a private subnet and return the response back to them. That's why we need to disable the source destination check for NAT instance.
There's more...
NAT instance does not support IPv6. To support NAT for IPv6 we need to create an Egress-Only Internet Gateway from the VPC console and attach it to main Route Table.