The Easiest Way to Deploy an NGINX Web Server on Amazon EC2 Instance with a User Data BASH Script

Chigozie Oziri
8 min readSep 9, 2023

--

Recently, I was given a simple test to deploy an NGINX web server on an Ubuntu Amazon EC2 instance using a user data BASH script, and I thought I should write about it. So let’s dive right in!

The easiest way to deploy Nginx web server on Amazon EC2, cover image
The Easiest Way to Deploy an NGINX Web Server on Amazon EC2 Instance with a User Data BASH Script

What would you learn?

Some of the things you would learn here include:

  • How to create a VPC
  • How to create a Security Group to allow HTTP traffic into your web server
  • How to launch an Amazon EC2 instance with the VPC and SG you have created
  • How to install and deploy an NGINX web page using a Bash script in the user data section of the Amazon EC2 configuration

Prerequisites

In order for you to tag along with this article, you would need the following:

  • An AWS IAM user account (it is not good practice to do this with your root account). If you do not have an AWS account, you can create one here.
  • Knowledge about how to navigate the AWS console.

Creating the Virtual Private Cloud (VPC)

In AWS, a VPC allows you to create your own private cloud. You can divide the VPC into private and public subnets. The public subnet is used to set up resources (e.g. a web server) that should be accessible to the public, while the private subnet is ideal for resources such as databases that should not be publicly accessible.

To get started, log in to your AWS IAM user account and navigate to your VPC dashboard using the Search bar. If you haven’t created a VPC before, a default VPC should have been created for you when you registered for your AWS account. However, it’s not recommended to use the default VPC for your project. Therefore, it’s better to create a new one dedicated to your project. Click the Create VPC button.

my VPC dashboard

In the VPC settings interface, select VPC and more, and in the Name tag auto-generation section, name it as desired e.g. “dev”. Ensure the box to the left of Auto-generate is checked.

Note: Consider naming VPC based on use (e.g. lab, development, testing, production, etc.) or specific project.

VPC configuration

In the IPv4 CIDR block section, change the CIDR notation from 10.0.0.0/16 to 10.0.0.0/24 to reduce the VPC size from 65,536 to 256 IPs. In the IPv6 CIDR block section, choose the No IPv6 CIDR block option. Leave Tenancy as Default. Set the Number of Availability Zones (AZs), Number of public subnets, and Number of private subnets to 2 each. Set the NAT gateways ($) and VPC endpoints to None. You can leave the two DNS options checked, and we will not need any Additional tags.

VPC preview

Based on the VPC preview in the snapshot above, we have

  • Four subnets: two private and two public, named after the Availability Zones (AZs) and the AWS Region you are working in (e.g. us-east-1). A subnet is a section of the VPC that can contain resources such as EC2 instances. As we can see from the VPC preview, each Availability Zone (AZ) consists of both a private and a public subnet, which is ideal.
  • Three route tables: A route table consists of routes that dictate network traffic direction.
  • One Network connection: To establish network connections with external networks, we utilize a single Internet Gateway named dev-igw. This gateway connects the VPC to the internet and hence requires attachment to the public route table. The Internet Gateway is vital in making a public subnet actually publicly accessible over the internet.

At the bottom of the page, click Create VPC and wait for it to get provisioned. You can see the details displayed on the Create VPC workflow page.

Create VPC workflow page
the Create VPC workflow page

You can view the Resource map and other details by clicking the View VPC button. However, for now, we are finished with VPC creation. Well done!

Creating the Security Group (SG)

The next step is to create a Security Group to allow HTTP traffic to the Amazon EC2 instance we will launch.

A Security Group is a virtual firewall that manages inbound and outbound traffic for an Amazon EC2 Instance.

Go to the Search bar and type in Security groups. Under the Features category, click Security groups on either the EC2 feature or the VPC feature.

Click the Create security groups button

On the Create security group page, enter a descriptive name for your security group. Next, enter a Description that states the main purpose of the security group. Click on the “x” mark in the VPC section and choose the VPC that matches the new VPC we created specifically for this project. This ensures that the security group is available in the same VPC as our project’s EC2 instance.

creation of security group
Choose the VPC we created in this article.

Next, click on the Add rule button. This action will open a new section where you can edit both the inbound and outbound rules for your security group. At the Inbound rules section, select the HTTP option from the Type dropdown menu and notice that the Port range field automatically updates to display the number 80, which is the port number for HTTP web traffic. Now, click on the Source field and choose Anywhere-IPv4. You can add a Description if you want to state the purpose of the new rule.

Under the Outbound rules section, set the Destination to Anywhere-IPv4, the Type to All traffic, the Protocol to All, and the Port range to All. This rule will allow all outbound traffic. At the bottom of the page, click Create security group.

allow HTTP and all outbound traffic

You have successfully learned how to create a VPC and Security Group. In the next section, we will launch an Amazon EC2 instance using them. You are making great progress!

Launching our Amazon EC2 Instance

Amazon EC2 provides secure, reliable, and scalable compute capacity in the cloud. Here, EC2 stands for Elastic Compute Cloud. Amazon EC2 instances are virtual servers on which we run applications in the cloud.

In the console, Search for EC2 and press Enter. This would open your EC2 dashboard where the details of your Amazon EC2 resources are displayed. Click Launch instance. In the Name and tags section of the Launch an instance page, enter a descriptive name for your EC2 instance. I prefer to name my EC2 instances based on their Operating System (OS) and server type, but it’s not a strict rule. Under the Application and OS Images (Amazon Machine Image) section, select the Ubuntu OS, and the Ubuntu Server 22.04 or 20.04 LTS (HVM), SSD Volume Type which is Free tier eligible. Leave the Architecture as 64-bit (x86).

Amazon EC2 instance launch
Launching an Amazon EC2 instance

At the Instance type section, choose the t2.micro which is also free tier eligible. In this demo, we will not need to log in to our instance, so at the Key pair (login) section, choose Proceed without a key pair (Not recommended).

AMI: ubuntu 22.04LTS; Instance type: t2.micro; Keypair: Proceed without a key pair (Not recommended)

Next, click Edit to modify the Network settings. Click the VPC dropdown button and choose the VPC we created here. Change the Subnet selection to any of the public subnets. Enable Auto-assign public IP. Under the Firewall (security group) section, choose Select existing security group so that we can select the SG we already configured instead of creating a new one. Click the Common security groups dropdown button, and select the SG we already created. Usually, every VPC comes with a default security group. Therefore, our custom security group will appear as the second option.

⚠️The network settings used here are only for demonstration purposes and are not suitable for production use cases.

EC2 network settings

Leave the Advanced network configuration, and the Configure storage sections in their default settings and proceed to the Advanced details section. Scroll down to the User data section and input the following code snippet:

#!/bin/bash

# UPDATE PACKAGE MANAGER
apt update --fix-missing

# INSTALL, START and ENABLE NGINX
apt install -y nginx
systemctl start nginx
systemctl enable nginx

# CHANGE FILE PERMISSION TO PERMIT MODIFICATION OF DEFAULT WEB FILE
chmod 0777 /var/www/html/index.nginx-debian.html

# MODIFY DEFAULT WEB DOCUMENT
echo "<html><h1>Hello from your web server!</h1></html>" > /var/www/html/index.nginx-debian.html

# RESTART NGINX
systemctl start nginx

After clicking Launch instance, wait for initialization to complete. Check that the Instance state is Running and the Status check shows 2/2 checks passed.

A completely initialized Amazon EC2 instance
A completely initialized Amazon EC2 instance

Click the checkbox to the left of the Name of your EC2 instance. In the Details tab that opens up, copy your instance’s Public IPv4 address and paste it on your web browser to view the web page. If you had clicked the blue “open address” button, you would have been directed to https://yourIP_address. As a result, you will not be able to view the web page. Instead, you can only access it at http://yourIP_address.

The final web page
The final web page!

Troubleshooting

If your web page is not loading for any reason, you can check the system logs of your EC2 instance by following the steps shown in the image below.

Navigation to system logs of EC2 instance

To get insight into why the deployment of your web page failed, follow these steps. First, select the name of your EC2 instance by checking the box to the left of it. Then, click on Actions and choose Monitor and troubleshoot from the dropdown menu. Finally, click on Get system log. This will provide you with useful information to troubleshoot the issue.

The system log of an Amazon EC2 instance

If you need to edit the Bash script content of your User data, first stop your instance by clicking on the “Stop instance” option in the “Instance state” dropdown menu. Then, click on the “Actions” button, select “Instance settings”, and choose “Edit user data” from the dropdown menu.

navigation to edit user data after the launch of EC2 instance
The navigation to edit user data after the launch of EC2 instance

The resulting page provides options for you to edit your user data as text or by importing a file.

editing the user data of an already launched EC2 instance
editing the user data of an already launched EC2 instance

Save your change(s) and click Start instance at the Instance state dropdown menu to restart your instance. Note that your instance may receive a new IP address at this point.

I hope this helps.

Conclusion

We have reached the end of our tutorial. Thank you for sticking around. Click here to learn more about AWS services. Consider following me for similar articles; clap if helpful. Your feedback matters. See you soon.

--

--

Chigozie Oziri
Chigozie Oziri

Responses (1)