How Nginx Helps in Load Balancing, Reverse Proxy, and HTTP Caching
Have you heard about Nginx in the first place? If you don’t know what Nginx is, then you’ve come to the right place.
What is Nginx?​
Nginx is a web server that handles Reverse Proxy, Load Balancing, and HTTP Caching.
That’s the definition, but it’s not enough, I know. Let’s dive deeper into defining each of these to a certain extent.
1. Proxy​
A Proxy is an intermediate agent that helps you access the server indirectly. In this scenario, you are accessing the server through the proxy server. The proxy server handles your request, sends it to the server, and then returns the response back to you. One common example would be a VPN. You can browse country-restricted content using VPNs, and they are pretty useful, aren’t they?
Now that you know what a proxy is, let’s understand some types of proxies.
1.1 Forward Proxy​
In this type of proxy, multiple users communicate with the same server, and the proxy agent forwards the requests to the same server.
1.2 Reverse Proxy​
Reverse proxy is particularly what Nginx does. If you have multiple servers running on different or the same machines and you need to access them from the same server, Nginx helps you with this efficiently.
For example, if your backend is running on localhost:8000
and your frontend application on localhost:3000
, you might want to access both at once from localhost:80
. Nginx can be configured to redirect users to the appropriate server based on the requested endpoint.
2. Load Balancing​
Load balancing is another major feature provided by Nginx. If multiple users request the same resource, Nginx will redirect the user to another server, balancing the load so the server won’t crash easily. Load balancing is often used with web applications. Nginx supports several load-balancing methods, including:
- Round Robin: Requests are distributed evenly across the servers.
- Least Connections: Requests are sent to the server with the fewest active connections.
- IP Hash: Requests from a particular client are always sent to the same server, ensuring session persistence.
By efficiently distributing traffic, Nginx ensures high availability and reliability, preventing downtime and improving the user experience.
3. HTTP Caching​
HTTP caching improves server performance by storing copies of requested web pages. When a user revisits a webpage, Nginx can serve the cached version, reducing latency and server load. Nginx’s caching capabilities can:
- Reduce Latency: Cached content can be served quickly without contacting the backend server.
- Improve Scalability: By reducing the load on backend servers, Nginx allows them to handle more simultaneous requests.
- Lower Bandwidth Usage: Serving cached content reduces the data that needs to be transferred from the backend server, saving bandwidth.
Nginx can cache both static content (like images, CSS, and JavaScript files) and dynamic content (generated by applications), providing significant performance boosts.
Setting Up Nginx​
If you are using Linux, you can install Nginx simply by running:
sudo apt-install nginx
If you are using another OS, you can browse online for the relevant download commands.
I prefer doing everything inside a Docker container because it’s easy to set up and run without messing with my computer.
Follow this to install Docker.
Running Nginx in a Docker Container​
After installation, follow the steps below:
docker run -it -p 8080:80 ubuntu
This command pulls an Ubuntu image from Docker Hub (an online repository that contains images). If the image is available locally, it will use that local image. Be sure that the Docker daemon is running—just open Docker Desktop to get it spinning. The -it
flag stands for interactive, meaning you can interact with that Docker image within the terminal. You can run it in detach mode, but more on that later. The -p
flag maps port 80 of that virtual Ubuntu machine to your local system port 8080, helping you access that port easily.
After installation, run:
apt-get update
apt-get install nginx
To verify the Nginx installation, use:
nginx -v
You can view that in your local machine by going to localhost:8080
.
You can find the Nginx config files inside the container with:
ls /etc/nginx/
Be sure to do this inside that container terminal. We need to change the nginx.conf
file to manage our Nginx server.
Basic Structure of Nginx Configuration​
A basic Nginx configuration file typically includes the following sections:
- Events Block
- HTTP Block
- Server Block
- Location Block
Events Block​
events {
worker_connections 1024;
}
The events block configures global settings that affect how Nginx handles connections.
worker_connections 1024;
specifies the maximum number of simultaneous connections that can be handled by a single worker process. This can be adjusted based on server capacity and expected load.
HTTP Block​
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_types text/plain application/xml;
}
The HTTP block contains directives that apply to all HTTP servers:
include mime.types;
includes the file that defines various MIME types, ensuring that files are served with the correct content type.default_type application/octet-stream;
specifies the default MIME type if none is found.sendfile on;
enables efficient file transfers.keepalive_timeout 65;
specifies the timeout for keeping connections alive.gzip on;
andgzip_types
enable and configure gzip compression for specified MIME types, improving performance by reducing response sizes.
Server Block​
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location /images/ {
alias /data/images/;
}
error_page 404 /404.html;
location = /404.html {
internal;
}
}
The server block defines the configuration for a virtual server:
listen 80;
specifies the port to listen on (port 80 is standard for HTTP).server_name example.com;
defines the domain name this server responds to.root /usr/share/nginx/html;
sets the root directory for requests.index index.html index.htm;
specifies the default files to serve if a directory is requested.
Location Blocks​
Location blocks define how different request paths are handled:
location / { try_files $uri $uri/ =404; }
: This block tries to serve the requested URI, checking if it’s a file or directory. If neither is found, it returns a 404 error.location /images/ { alias /data/images/; }
: Requests to/images/
are served from/data/images/
.error_page 404 /404.html;
: Defines a custom 404 error page.location = /404.html { internal; }
: The custom 404 page is only accessible internally, not directly by users.
Putting It All Together​
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_types text/plain application/xml;
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location /images/ {
alias /data/images/;
}
error_page 404 /404.html;
location = /404.html {
internal;
}
}
}
Testing and Reloading Nginx​
To test the configuration, use:
nginx -t
For reloading, use:
nginx -s reload
This typical Nginx configuration file showcases the essential components needed to set up a basic web server:
- Events Block for connection settings.
- HTTP Block for general HTTP settings and compression.
- Server Block for virtual server configuration.
- Location Blocks for handling different request paths and custom error pages.
Understanding and customizing these components can help you optimize your web server for better performance and reliability.
Summary​
This Nginx configuration is designed to route traffic efficiently:
- Requests to the root path are proxied to a web application.
- Static content is served directly from a specified directory.
- API and admin requests are proxied to another backend server with specific headers and timeout settings to handle long-running requests.
- Media files are served from a designated directory.
Conclusion​
Setting up Nginx can take some time, but it is beneficial if you want the features mentioned above. Stay tuned for more interesting blogs on technology. That’s all