Nginx.

Nginx logo

Everybody talks about it.

Nobody really knows what it does.

a character confused about what nginx does

But it’s easy to be confused.

Because Nginx can do all of it and do it well.

It creates web servers that are lightweight, fast, and efficient.

fast web server

It’s used as a reverse proxy to handle millions of incoming traffic.

handle millions of incoming traffic

This year, it powers over 33% of the web.

Let’s see how it works.

Create a web server

Nginx web servers work exactly like any others you created with Node.js or Django.

But instead of writing JavaScript, you modify the nginx config file.

Let’s create an HTTP server that listens on PORT 3000.

nginx config

The config file consists of directives.

There are two types of directives:

  • A block directive contains more directives

  • Simple directive that is a key-value pair

To make a functioning web server, we need to handle the request and response.

nginx config

Now any request to the root URL would return a “hello world” text and a status code 200.

The same Node.js code would look like this:

nodejs code

It’s cool but nothing special.

A more common use case of Nginx is a reverse proxy.

This is where it really shines.

Reverse Proxy

What’s a reverse proxy?

A proxy is like a vpn for clients.

proxy

A reverse proxy is a vpn for servers.

reverse proxy

It reroutes requests from clients to the servers.

Why the extra step?

  • Security: Just like the reason you use vpn, you use a reverse proxy to hide the servers’ IP addresses to make it more secure

  • Caching

  • Load balancing: distributing client requests to multiple servers that are capable of returning the same content.

It’s very easy to create a reverse proxy in Nginx.

First, create another block.

proxy pass

Notice the only change here from the previous example is that we are using proxy_pass instead of returning a text.

Instead of handling the request, we pass it to a server with the IP address “127.0.0.1:4000.”

Before:

nginx as a web server

After:

nginx as a reverse proxy

But more often, we want to use it as a load balancer and route the requests to three different servers.

So, let’s create a group of servers called “backend_servers.”

upstream

Then route the requests to this group of servers:

nginx config (final)

And you have just created a reverse proxy server with Nginx.

Fee from Anime Coders

How did you like today's email?

Login or Subscribe to participate

Keep Reading