iverse.deviverse.dev

nginx, and why it sits in front

Jem Young4 min

tl;dr

A web server takes an incoming request and decides where it goes. nginx is written in C, does compression, SSL and load balancing as its day job, and will always be faster at this than Node.

Your server is updated, hardened, and still answers nothing. It needs a web server: the thing that takes a request off the wire and decides where it goes — an application, a database, another machine entirely.

Two serious options. Apache has deep built-ins and works well with Java and PHP out of the box. nginx — pronounced engine-x, which nobody guesses the first time — is a web server, a reverse proxy, a forward proxy, an email proxy, and it's written in C.

A request from the internet arriving at nginx on port 80 and being proxied to a Node app on port 3000, with a dashed line showing the direct route as a bad idea.
You can point the internet straight at Node. It works, and you give up everything below.

The obvious question is why bother, since Node can serve the request itself.

Install and look at it

sudo apt install nginx
sudo service nginx start

Visit your IP and you'll get the nginx welcome page. Then go read the default config, which lives where all config lives:

less /etc/nginx/sites-available/default

nginx configs are their own small language, and every line has a reason. The pieces worth recognising now:

rootthe base directory requests are served from — /var/www/html
locationa path block. / is the root, like a filesystem
directivesthe instructions inside a block, e.g. try_files, proxy_pass

Make it yours

That welcome page is just a file. Replace it:

sudo vi /var/www/html/index.html

nginx picks up index.html before the Debian default, so hello world is enough. If a static page is all you need, you are already finished — nginx serves HTML perfectly well on its own.

Next: putting a Node application behind it.

← all Full Stack Fundamentals, v3 posts