Install Nginx in Ubuntu

Nginx is a web server, which can be used to serve dynamic HTTP content. Installing nginx is quite easy but configuring it might be a bit challenging for a newbie.

Install nginx

Run the following command and it will nginx.

sudo apt install nginx

Verify installation

After installation, the web server is started automatically. But we can check the web server status using the following command. This will display some text including words like Running, Ok etc., which indicates the server is started successfully and it’s running.

systemctl status nginx

And if nginx server is started successfully then accessing the site through Domain Name or IP address in a web browser will display Welcome to nginx page.

If nginx server can't start because of any error then we can know about the related error by running the following command.

sudo nginx -t

Start/Stop/Restart nginx server

Following are the commands to start/stop/restart the nginx server.

sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx

Configure nginx server for node.js service

Create a new server block and configure server block by setting server name and location values. You can replace “nodejs” with any suitable name in the following command.

sudo vi /etc/nginx/sites-available/nodejs

Set server name and location values as below. You need to set your domain and port in the following code.

  • server { 
        listen 80; 
        server_name domain.com; # set domain name here..
    
        location / 
        {
            proxy_set_header   X-Forwarded-For $remote_addr;
            proxy_set_header   Host $http_host;
            proxy_pass         "http://127.0.0.1:3000"; # set port
        }
    }
    
  • Create a link from this file to the sites-enabled directory. Nginx will use this link file while starting the server. Make sure you replace “nodejs” with your server block name in the following command.

    sudo ln -s /etc/nginx/sites-available/nodejs /etc/nginx/sites-enabled/

    It’s all done now. Just start your node.js service and restart the nginx server. You should be able to access your nodejs service by domain URL in a web browser now.

    sudo systemctl restart nginx