Nginx Basics

what is Nginx?

NGINX is open-source web server software used for reverse proxy, load balancing, and caching. It provides HTTPS server capabilities and is mainly designed for maximum performance and stability. It also functions as a proxy server for email communications protocols, such as IMAP, POP3, and SMTP.

Understanding Nginx

using nginx via ubuntu container with docker so that we can see the file system and understand its internals

docker run -it -p 8080:80 ubuntu:latest # This will start ubuntu container with interactive terminal

Now in the terminal of ubuntu container -

apt-get update # this will install necessary packages
apt-get install nginx
apt-get install vim # installing vim editor to edit our files you could use nano if you want

Now after installing nginx you will see etc/nginx folder in user etc directory.

In here our main concern is nginx.conf file, as for what behaviour we want from our nginx server is decided by this config file.

The config file has following blocks -

  • events

  • http

    • server

      • location
    • upstream

  • stream

    • udp

    • tcp

Now delete all the content in nginx.conf file. so that we can understand it from scratch

Using Nginx

Serving Static Files


events {

}

http {
    # this will initiate a server that will be able to serve static files
    server {
        listen 80;
        server_name _;
        location /hello {
            return 200 "hello";
        }
        location /world {
            return 200 "world";
        }
    }
}

after making above changes to the file, reload the nginx server using following command

cd etc/nginx # we need to be nginx folder to reload
nginx -s reload # reloading our nginx serve with new config

and now if you go to that path in your browser …

now that you have gotten gist of it, we will be using the nginx image directly rather than using nginx by installing it on ubuntu container

version: '3.9'
services:
  nginx:
    image: nginx:latest
    container_name: nginx_basics 
    ports:
      - "8080:80"
    environment:
      - NGINX_PORT=80 
      # this is the default port our server will be running on
    volumes:
      - ./website:/etc/nginx/website
      # this copies the website folder that has our static files
      # to the container at localtion etc/nginx/website

      - ./nginx.conf:/etc/nginx/nginx.conf
      # this volume copies our config from this folder
      # that we wrote to the etc/nginx folder in nginx container
events {
}
http {
    server {
        listen 80;
        server_name _;
        root /etc/nginx/website; 
        # Root tells us where to look / what dir to be in
    }
}

Load Balancing

This blog is still incomplete i will try to complete it soon …