I recently bumped into my own post from some time ago in which I describe how to add a NAT instance to your private subnet to have access to the Internet to install packages, etc. Although this still works, some time ago AWS introduced the NAT Gateway, which, in most cases, makes life much easier.
In this post, I'll show you how to set up the NAT Gateway instead of using the NAT instance. To get started with the same situation as the original post, I created this CloudFormation script that creates a VPC with two private and public subnets. When these are in place, I can create an EC2 instance in both the private subnet and in the public one, as I also described in the original post.
What we see is that the ‘sudo yum update’ in the ‘PrivateInstance’ fails as expected because the private instance isn’t allowed to access the Internet to install packages. So that is where the NAT Gateway comes in place. To install one, I simply use the wizard in the Management Console, which will guide you through the process.
Select the ‘NAT Gateways’ option in the left menu to start the wizard:
In the next screen, select a public subnet in which the NAT Gateway has to reside and select an Elastic IP address for it (most likely you will need to create one as you won’t normally have these available):
Then, the NAT Gateway is created (yes, it has become that easy) and we need to modify the Route Table for the private subnet so it will make use of the NAT Gateway. Just click the button in the screen that is shown after the creation:
In the private route table, add a rule that connects our private subnet to the Destination ‘0.0.0.0/0’ (which means any machine) via the NAT Gateway by selecting the NAT as the target:
That’s it. Now we can access the internet from our ‘private’ instances as we could with the NAT instance in place. So the question might be when to use one over the other. To answer that question AWS has made the following comparison so you can check what is your use case and see what fits best.