Devops

How to install Nginx on an EC2 Instance?

Description of the image

Nginx, popularly known as “ engine- x, ” is an important, open-source simple web server known for its effectiveness, scalability, and point set. Installing Nginx on an Amazon EC2 instance allows you to host websites and operations within the robust AWS  structure. It is mostly used for reverse proxy.

Prerequisites

Before starting the installation of the nginx server you must have the following with you:

  • An AWS account with access to the EC2 instance.
     
  • An existing EC2 instance runs a compatible Linux Distribution (Amazon Linux 2, Ubuntu, etc.). The instance must have SSH access enabled.
     
  • An SSH  customer like PuTTY( Windows) or the erected-in terminal( macOS/ Linux) can connect to your EC2 case. 
     
  • A basic understanding of Linux commands and file editing.

Step 1: Connect to your EC2 Instance

  • Locate your Public DNS (IPv4) address: Log in to the AWS account and navigate to the EC2 dashboard. Select your instance and find the “Public DNS (IPv4)” address under the “Description” tab. You will use this address to connect to your instance via SSH.
     
  • Connect using SSH: Open your preferred SSH client. Enter the following command, replacing <username> with your instance username and <public_dns> with your obtained address.
     
  • Enter your private key passphrase (if applicable): If you used a key pair for SSH access during instance creation, enter the key passphrase when prompted.

Step 2: Update and Upgrade the System

Maintaining an updated system is pivotal for security and stability. Run the following commands to modernize the package lists and upgrade existing packages. 

sudo yum update # For Amazon Linux
sudo apt update # For Ubuntu

Important: The update command used will depend on your specific Linux distribution.

Step 3: Install Nginx.

Let’s install Nginx using the appropriate package manager for your chosen distribution:

Nginx Server in Amazon Linux 2:

sudo amazon-linux-extras install -y nginx1.

This command will download and install Nginx's latest and most stable version from the sanctioned depository. 

Nginx Server in Amazon EC2 Ubuntu

sudo apt install nginx #installation process of ngnix web server

Step 4: Verify Nginx Installation

Once the installation is complete, you can verify it by checking the version: 

Sudo nginx -v #verify nginx web server

This command will give you the information on the installed Nginx version.

Step 5: Configure Nginx (Basic Setup)

Nginx configuration files reside in the directory/etc/nginx. The main configuration file is nginx. Conf. We will create a simple server block to serve a basic welcome page.

Create a Server Block File:

Use a text editor like Nano to create a new server block file: 

Sudo nano /etc/nginx/sites-available/default #configuration of nginx web server

Paste the Configuration:

With the creation of the new file, paste the following basic server block configuration:

server {
    listen 80 default_server;  # Listen on port 80 (HTTP)
    server_name _;              # Handle all requests

    location / {
	proxy_pass http://localhost:8001;
        root /var/www/html;
        index index.html index.htm;
    }

    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
}
#This is also used for proxy server and reverse proxy
#if app run on 8001 then security group also need to open

Explanation:

  • Listen 80 default_server; Defines the port (80 for HTTP) and sets this block as the default server.
     
  • server_name _; Handles all requests directed to the server's IP address.
     
  • Location / { ... }: Defines a location block for the root path (/).
     
  • Root/var/www/html: Set up the document root directory where your website files reside. You should create this directory if it doesn't exist.
     
  • Index index.html index.htm: Specifies default index files to serve when a directory is requested.
     
  • error_log /var/log/nginx/error.log; Defines the location for error logs.
     
  • access_log /var/log/nginx/access.log; Defines the location for access logs, recording user requests.
  • check for the security group

Save and Close the File:

Press Ctrl+O to save the file, then Ctrl+X to exit the editor.

Enable The Server Block:

Use the following command to produce a symbolic link from the recently created server block file to the spots-enabled directory, effectively enabling it. 

sudo ln -s /etc/nginx/sites-available/default/etc/nginx/sites-enabled/

Step 6: Start and Manage the Nginx Web server

  • Restart Nginx: Once you are confident about the configuration, restart Nginx to apply the changes: 
sudo systemctl restart nginx  # For systemd-based systems (Amazon Linux 2)

sudo service nginx restart     # For Upstart-based systems (older Ubuntu versions)
  • Verify Nginx Status: Check the status of Nginx to ensure it is running correctly:
sudo systemctl status nginx  # For status of web server

sudo service nginx status     # For Upstart-based systems
  • Optional: Secure  Nginx with a Firewall

By default, Nginx acts on port 80 (HTTP). If you haven’t configured a firewall on your EC2 instance, it is crucial to open port 80 to allow incoming web traffic. You can achieve this using the AWS Security Groups feature.

Step 7: Serving Your Website Content

The previous steps set up Nginx to serve an introductory welcome message. To serve your website content, follow these steps:

  • Create a Document Root Directory: Create a directory to store your website files. A typical location is  /var/www/html. You can use the following command to create it:
sudo mkdir -p /var/www/html
  • Upload Your Website Files: Use a secure train transfer system like SCP or SFTP to upload your website lines( HTML, CSS, JavaScript, etc.) to the document root directory(/ var/ www/ html). 
     
  • Verify File Permissions: Ensure the web server user (usually nginx) has read permissions for your website files. You can use the chown and chmod commands to adjust permissions if necessary.
     
  • Reload Nginx: After uploading the files, reload the configuration and inform Nginx about the changes. 
Sudo systemctl reload nginx  # For systemd-based systems
sudo service nginx reload     # For Upstart-based systems

How to install Nginx with Ansible?

If you want to install nginx with Ansible, you can create a playbook that will define the task and that will be necessary to install the nginx on the targeted server.

Step 1: Create an Ansible playbook file 

# install_nginx.yml

- name: Install Nginx
  hosts: your_target_servers
  become: true  # Run tasks with root privileges

  tasks:
    - name: Update apt package cache (for Debian/Ubuntu)
      apt:
        update_cache: yes
      when: ansible_os_family == 'Debian'

    - name: Install Nginx
      package:
        name: nginx
        state: present

    - name: Start Nginx service
      service:
        name: nginx
        state: started
        enabled: yes

Step 2: Run the playbook

ansible-playbook -i your_inventory_file install_nginx.yml

How to Install Nginx in a Container?

To install Nginx in a container, you can use Docker.

Step 1:  Install Docker

https://www.docker.com/products/docker-desktop/

Step 2: Create a Dockerfile

# Use the official Nginx image from Docker Hub
FROM nginx

# Copy custom configuration file (if needed)
# COPY nginx.conf /etc/nginx/nginx.conf

# Expose port 80
EXPOSE 80

Step 3: Build the Docker image

docker build -t my-nginx .

Step 4: Run the Docker container

docker run -d -p 8080:80 --name my-nginx-container my-nginx

How to install Nginx on EC2 using Terraform?

Step 1: Create Terraform Configuration

provider "aws" {
  region = "your_aws_region"
}

resource "aws_instance" "nginx_server" {
  ami           = "ami-12345678"  # Replace with your desired AMI ID
  instance_type = "t2.micro"      # Replace with your desired instance type

  tags = {
    Name = "nginx-server"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx"
    ]
  }
}

Step 2: Initialize Terraform

terraform init

Step 3: Apply Terraform Configuration 

terraform apply

How to install Nginx on EC2 using Yum?

Step 1: Connect to Your EC2 Instance

ssh -i your-key.pem ec2-user@your-ec2-instance-public-dns

Step 2: Update the Packages

sudo yum update -y

Step 3: Install Nginx

sudo yum install nginx

Step 4: Start the Nginx service

sudo systemctl start nginx

Step 5: Enable Nginx to start on boot

sudo systemctl enable nginx

Add SSL/TLS to Secure Your Server

Step 1: Install Certbot

sudo amazon-linux-extras install epel -y
sudo yum install certbot -y

Step 2: Obtain a Certificate

sudo certbot --nginx -d yourdomain.com

Step 3: Renew Certificates Automatically

sudo crontab -e
# Add the following line:
0 0,12 * * * /usr/bin/certbot renew --quiet

Common issues during Nginx installation on an EC2 instance and their solutions

IssueSolution
Permission Denied ErrorsUse sudo to run commands with elevated privileges.
Package Not FoundUpdate package lists with sudo apt-get update before installing Nginx.
Port 80 is Already in UseCheck running services with sudo lsof -i :80 and stop conflicting services.
Firewall Blocking TrafficAllow traffic through the firewall with sudo ufw allow 'Nginx Full'.
Nginx Not StartingCheck logs in /var/log/nginx for detailed error messages.
Incomplete InstallationEnsure all dependencies are installed by running sudo apt-get install -f.

Securing Nginx with SSL/TLS

StepDescription
Obtain SSL/TLS CertificatesUse Let's Encrypt or a commercial certificate authority (CA) to get SSL/TLS certificates.
Install CertbotInstall Certbot, a tool to obtain and manage SSL/TLS certificates from Let's Encrypt: sudo apt-get install certbot python3-certbot-nginx.
Configure Nginx for SSLEdit the Nginx configuration file to include the SSL certificate and key paths: server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem; }
Automate Certificate RenewalSet up a cron job to automatically renew certificates: 0 3 * * * /usr/bin/certbot renew --quiet
Enable HTTP/2Modify the Nginx configuration to support HTTP/2 for improved performance: listen 443 ssl http2;

Configuring Firewalls

StepDescription
Install UFW (Uncomplicated Firewall)Install UFW if not already installed: sudo apt-get install ufw.
Allow OpenSSHAllow OpenSSH to maintain access: sudo ufw allow OpenSSH.
Allow Nginx TrafficEnable Nginx Full profile to allow HTTP and HTTPS traffic: sudo ufw allow 'Nginx Full'.
Enable UFWEnable the firewall: sudo ufw enable.
Check Firewall StatusVerify the firewall status and rules: sudo ufw status.

Advanced Configurations

Load Balancing

StepDescription
Define Upstream ServersSpecify backend servers in the http block: upstream backend { server backend1.example.com; server backend2.example.com; }
Configure Load BalancerUse proxy_pass to direct traffic to the upstream block:location / { proxy_pass http://backend; }

Caching

StepDescription
Enable CachingConfigure caching in the server block: proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m;
Cache SettingsDefine cache parameters in the location block: location / { proxy_cache my_cache; proxy_pass http://backend; }

Reverse Proxy

StepDescription
Set Up Reverse ProxyForward client requests to backend servers: location / { proxy_pass http://localhost:8080; }
Additional Proxy SettingsOptimize with settings like:proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;

Monitoring Nginx Performance and Managing Logs

Monitoring Tools

ToolDescription
Prometheus and GrafanaPrometheus collects metrics, and Grafana visualizes them. Use nginx_exporter to gather Nginx metrics.
New RelicProvides detailed data on application performance, including Nginx monitoring.
DatadogOffers monitoring with built-in Nginx integrations for real-time analytics.

Log Management

TechniqueDescription
Log RotationUse tools like logrotate to manage log file sizes and rotation schedules.
Centralized LoggingImplement ELK Stack (Elasticsearch, Logstash, Kibana) to aggregate and analyze logs.
Custom Log FormatsCustomize log formats in Nginx configuration to capture relevant data:log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

Useful commands for Nginx

TaskScript
Update Package Index
sudo apt update
Install NGINX
sudo apt install nginx -y
Start NGINX Service
sudo systemctl start nginx
Enable NGINX on Boot
sudo systemctl enable nginx
Check NGINX Status
sudo systemctl status nginx
Restart NGINX Service
sudo systemctl restart nginx
Stop NGINX Service
sudo systemctl stop nginx
Reload NGINX Configuration
sudo systemctl reload nginx
Set Up Firewall
sudo ufw allow 'Nginx Full'
Create Basic Configuration
echo -e "server {listen 80;server_name example.com;location
/ {root /var/www/html;}}" > /etc/nginx/sites-available/default
Test NGINX Configuration
sudo nginx -t
Automate Installation and Setup
#!/bin/bash\nsudo apt update 
sudo apt install nginx -y 
sudo systemctl start nginx 
sudo systemctl enable nginx 
sudo ufw allow 'Nginx Full'

Automation Script for Nginx

#!/bin/bash
# Update package index
sudo apt update

# Install NGINX
sudo apt install nginx -y

# Start NGINX service
sudo systemctl start nginx

# Enable NGINX to start on boot
sudo systemctl enable nginx

# Allow HTTP and HTTPS traffic through the firewall
sudo ufw allow 'Nginx Full'

# Create a basic server block configuration
echo -e "server {
    listen 80;
    server_name example.com;
    location / {
        root /var/www/html;
    }
}" | sudo tee /etc/nginx/sites-available/default

# Test NGINX configuration
sudo nginx -t

# Reload NGINX to apply configuration changes
sudo systemctl reload nginx

Some Additional Considerations

Virtual Hosts

You must configure virtual hosts within Nginx to host multiple websites on the same server. This allows different content to be served based on the domain name accessed.

Security

While the basic setup is a starting point, consider implementing additional security measures, such as setting up a firewall and configuring SSL/TLS certificates for HTTPS encryption.

Advanced Configuration

Nginx offers a wide range of features and configuration options. Explore the official Nginx documentation for details on load balancing, caching, and other functionalities.

This guide will provide a holistic overview of configuring and installing Nginx on your EC2 instance. Remember to adapt the configuration to your specific needs and website requirements. By following these steps and exploring further resources, you have exercised Nginx's power and flexibility to host your web applications on the AWS cloud. By the above guide, you can simply install Nginx and nginx configuration on your machine.

Note: You can go through the YouTube video for installing Nginx configuration and install nginx on ec2 instances

Click the Below link to read more about Nginx Server

https://devopsden.io/article/what-is-nginx

Follow us on

https://www.linkedin.com/company/devopsden/

Table of Contents

    Subscribe to Us

    Always Get Notified