We seldom land in a situation where we have applications/databases in private network and we need to patch or do any kind of maintenance activity where internet access is required, to overcome such situations, we can use AWS NAT Gateway.
The Network Address Translation (NAT) Gateway can be used in a scenario where we have both Public and Private subnet/network and you want the EC2 instance residing in private network to communicate to the internet preventing it from initiating a connection with those instances. In such scenarios, we can use a NAT Gateway, so that the internet traffic routes via NAT Gateway placed in public network.
There would be charge for creating and using a NAT gateway including the elastic IP address.
NAT Gateway Prerequisite:
Below are the prerequisites before moving on for creating NAT Gateway in AWS environment.
- A Public and Private subnet to be created in a VPC.
- Public subnet in which the NAT gateway to be placed.
- The Elastic IP address should be handy before moving on for provisioning the NAT Gateway. However the same can be created while provisioning the NAT Gateway. The Elastic IP address cannot be changed once it is associated with the NAT Gateway.
Create a NAT gateway
To create NAT gateway, from the AWS portal, looking at the prerequisite mentioned above, at first lets create an Elastic IP address.
- Go to AWS Services and type VPC and click on VPC.
- Under the VPC, Click on Elastic Ips, and click on Allocate Elastic IP address
- Select the default option and click on Allocate.
- An Elastic IP 188.8.131.52 is allocated.
- Now lets create the NAT Gateway.
- Under the VPC section, select the NAT Gateways and then click on Create NAT Gateway.
- Under the subnet section, select the public subnet (10.0.2.0/24) and the newly created Elastic IP address.
- The NAT Gateway is created.
Now the Next is to update the route tables.
As we have already created two subnets, Private (10.0.1.0/24) and Public subnet (10.0.2.0/24). Since we created the NAT Gateway in Public subnet, we need our EC2 instance in private subnet to have internet access, we need to create a route in private subnet.
Select the Route Tables, in Route Tables select the PrivateRouteTable, select Routes and edit the routes to update the NAT Gateway entry.
We updated the destination (0.0.0.0/0) and the target as the NAT Gateway, now save the routes.
We have created two instances, DB Server in private subnet (10.0.1.0/24) with IP 10.0.1.89.
The other instance which is FE Web Server in public subnet (10.0.2.0/24) with IP 10.0.2.31.
We created two Security Groups, one for the FE Web Server and other one is for DB server, we need to update the inbound and outbound rules of the security group.
Now lets ping google.com from the DB Server (10.0.1.89), which is in private network (10.0.1.0/24).
Excellent… the DB Server is now connected to Internet via NAT gateway.
Please refer on Troubleshooting NAT gateways