NGINX - A Complete Guide
NGINX - A Complete Guide
Introduction:
Understanding NGINX is essential for anyone involved in using web technology for
personal projects or large scale enterprise applications. This article will explain
what Nginx is, what it is used for, and also a hands-on demo which will run a
simple Nodejs application, configure nginx, also secure the application using
SSL/TLS certificate.
Overview:
What is NGINX ?
What is NGINX ?
NGINX is an open source web server software which is fast, lightweight and
provides high performance used to serve static files. When Nginx was introduced
in the initial release it functioned for HTTP web serving. However today it is used
as a reverse proxy, load balancing, caching, and health checks.
One of nginx’s primary function is to serve static content delivery which includes
HTML, CSS and JavaScript. When a user requests a web page, nginx locates and
serves the necessary static content. It can also handle multiple requests
concurrently, ensuring maximum performance under heavy load.
As the web grew in popularity, single servers began receiving millions of requests.
To handle this load, multiple servers became necessary. But how do we determine
which server handles which request? This is where NGINX acts as a load balancer.
Positioned at the entry point, it distributes incoming web traffic across multiple
servers. This approach ensures that no single server becomes a bottleneck,
allowing requests to be served efficiently. The distribution of the load depends on
the configured algorithm. For example, it might use simple logic like "least
connections" or "round robin."
3. NGINX as Caching
4. NGINX as Security
The proxy server acts as a single entry point that is publicly available, protecting
all other web servers and minimizing their exposure. So one can focus on this one
single entry point protecting. Nginx also handle SSL/TLS termination and
encryption ensuring secure client and server communication. So when an
encrypted data is sent to the proxy, even if attacker tries to intercept, they cannot
read the message.
5. NGINX as Compression
Configuring Nginx involves changing the Nginx Configuration files to customize its
behavior.
location.
3. The nginx configuration file consists of multiple block, directives. Each block
defines specific content.
Common Blocks:
Common Directives:
listen: Specifies the IP address and port that Nginx should listen on
root: Sets the root directory where Nginx will look for the files to serve
index: You can customize the index files. By default, Nginx has index.html,
index.htm, index.php in this list
try_files: Defines the order in which Nginx should try different URI paths.
Examples:
server{
listen 80;
server_name example.com;
location / {
root /var/www/example.com;
index index.html index.htm;
}
}
server{
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend_server_address;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_fo
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server{
listen 80;
server_name example.com www.example.com;
server {
listen 443 ssl;
server_name example.com www.example.com;
#SSL Configuration
ssl_certificate /etc/letsencrypt/live/example.com/fullch
ssl_certificate_key /etc/letsencrypt/live/example.com/pr
#Security headers
add_header Strict-Transport-Security "max-age=31536000;
location / {
root /var/www/example.com;
index index.html index.htm;
}
http {
upstream myapp {
least_conn;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://myapp1;
}
}
}
5. NGINX as Caching
http {
# ..
proxy_cache_path /data/nginx/cache keys_zone=mycache:10m
}
The time indicates how long the cache should be stored before its refreshed.
Ingress Controller is a specialized load balancer that watches for the ingress
resource and then proceeds the rules which is defined within it. Kubernetes
Ingress provides a centralized and efficient way to manage the external access to
services running within a kubernetes cluster. Kubernetes Ingress is specifically
designed for kubernetes environments, enabling advanced traffic management for
containerized applications.
NGINX vs Apache
Both were released as a basic web servers, later added more functionalities which
we have discussed earlier.
Choose NGINX
High performance
Static Content
Choose Apache
Shared Hosting
Customizable Solutions
Dynamic Content
Hands-on Demo
Title: Build a simple Node.js Application which serves static files, dockerize it,
configure Nginx, test load balancing and finally encrypt connection with https.
Steps:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-s
<title>Welcome to DevOps Insights by BALA VIGNESH</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
color: #333;
}
header {
background-color: #4CAF50;
padding: 10px 20px;
text-align: center;
color: white;
}
nav {
display: flex;
justify-content: center;
padding: 10px;
background-color: #333;
}
nav a {
color: white;
padding: 10px;
text-decoration: none;
}
nav a:hover {
background-color: #ddd;
color: black;
}
.container {
padding: 20px;
}
footer {
text-align: center;
padding: 10px;
background-color: #333;
color: white;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<h1>Welcome to DevOps Insights by BALA VIGNESH</h1>
</header>
<nav>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</nav>
<div class="container">
<h2>Your Gateway to DevOps Insights</h2>
<p>At DevOps Insights, I share my journey, knowledge, an
<p>Connect with me on <a href="https://www.linkedin.com/
</div>
<footer>
<p>© 2024 DevOps Insights. All rights reserved.</p>
</footer>
</body>
</html>
3. Create another file in the same location which is called about.html, and paste
the below code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-s
<title>About - DevOps Insights/title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
color: #333;
}
header {
background-color: #4CAF50;
padding: 10px 20px;
text-align: center;
color: white;
}
nav {
display: flex;
justify-content: center;
padding: 10px;
background-color: #333;
}
nav a {
color: white;
padding: 10px;
text-decoration: none;
}
nav a:hover {
background-color: #ddd;
color: black;
}
.container {
padding: 20px;
}
footer {
text-align: center;
padding: 10px;
background-color: #333;
color: white;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<h1>About DevOps Insights/h1>
</header>
<nav>
<a href="index.html">Home</a>
<a href="about.html">About</a>
</nav>
<div class="container">
<h2>About Me</h2>
<p>I am a DevOps engineer who is passionate about sharin
<p>Through my blogs and articles, I delve into various a
<p>Feel free to connect with me on <a href="https://www
</div>
<footer>
<p>© 2024 DevOps Insights. All rights reserved.</p>
</footer>
</body>
</html>
4. Create a backend web server using the index,js file. Copy the below code into
it.
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.21.0"
}
}
npm install
9. Now you can see that the dependencies are installed. Next step is to run the
application.
node index.js
FROM node:14-alpine
WORKDIR /app
COPY . .
EXPOSE 3000
7. We will achieve the same using Docker Compose. Docker Compose is a tool
which is used to run multiple containers easily.
version: '3'
services:
app1:
build: .
environment:
- APP_NAME=App1
ports:
- "3001:3000"
app2:
build: .
environment:
- APP_NAME=App2
ports:
- "3002:3000"
app3:
build: .
environment:
- APP_NAME=App3
ports:
- "3003:3000"
build: . Build the image using the Dockerfile in the current directory.
docker-compose up --build -d
12. You can individually check the site with all the ports running. You can also
check the logs and understand about each containers.
upstream: A block that defines a group of backend servers for load balancing.
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
http://localhost:8080
10. Let us check to which server is the request getting forwarded to.
11. Open the localhost with port 8080, and check the developer tab. Clear the
cache and check the network tab to see the server as Nginx. This means that
the request is going through Nginx.
12. If you open the localhost with port 3003, in the network tab you can see there
is no server configuration displayed. This means that the request is going
directly to the 3rd server.
13. In real life only the Nginx port will be open rest all the ports where the backend
server is running will never be exposed and it won’t be accessible. It will only
be accessible through Nginx as it is more secure since it will have only one
entry point.
1. Use Let’s Encrypt (A Certificate Authority) using Certbot which issues free
certificates. However, you need to have a Domain for this type. This is used for
production type cases.
2. Use Self-Signed Certificate. This is not a perfect solution though, it will show a
warning that they have a certificate but it is not issued from a Certificate
Authority. This is often used for testing and development.
In this article, we will be using the 2nd option as we are using for testing purpose
only.
Self-Signed Certificate
1. Create a folder to store the certificate files in your system.
mkdir nginx-certs
cd nginx-certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ngin
-out nginx-selfsigned.crt: Output file for the self signed certificate and public
key
Country Name: IN
State:
Locality
Organization Name:
Common Name:
Email:
You can leave some of the fields empty, and press Enter in the end.
4. Type ls and you can see both the certificate file and the private key.
server {
listen 443 ssl; # Listen on port 443 for HTTPS
server_name localhost;
Added additional server block for port 8080 and redirected, so that someone
who is trying to access the application in http gets redirected to https secure
connection.
2. Open your browser and try to access the localhost with port 443.
As you can see the site gets loaded with https, but since it is a self signed
certificate it shows it is not a valid certificate.
3. You can also try to access the site on localhost:8080 which will redirect to the
secured https site.
4. By the way, the default port for http is port 80. You can make the change in the
config file and see the changes.
This is how one can use Nginx as a reverse proxy server no matter which tech
stack you’re using.
This completes our comprehensive guide on NGINX.
Clean Up:
Conclusion:
In this article, we have explored what NGINX is and how it can be used and all its
features including a Hands-on demo which makes easy to understand the working
process.
NGINX is an open source web server software. Due to its simple setup and
extensive documentation NGINX is very well suited for beginners. It has many
features as seen above such as handling of static files, load balancing, caching,
compression and SSL/TLS. These features and its scalability makes NGINX more
popular and ideal for modern day web infrastructures.
👍
If you found this post useful, give it a like
Repost ♻️
Follow @Bala Vignesh for more such posts 💯🚀