DEV Community

Harrsh Patel
Harrsh Patel

Posted on • Originally published at harrsh.com

Multiple server with Nginx

Part 1 - Get server instance

  • Create a Ubuntu server with any provider like AWS, Linode, DigitalOcean, etc.

  • Add a ssh key.


Part 2 - Get domain name

  • Get a domain name from any provider like BigRock, Google, etc.

  • Add an A record with the ipv4 address of the server.

  • You can add multiple A records with different subdomains with the same ipv4 address.

Add the records in your domain provider DNS only. Don't create new domain in the server provider.


Part 3 - Server connection from local machine

  • Login via ssh.

  • Run the following commands,

sudo apt update

sudo apt upgrade -y
Enter fullscreen mode Exit fullscreen mode
  • Reboot your instance.

  • Login again via ssh.

  • Install Node.js via,

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

sudo apt install nodejs

node --version
Enter fullscreen mode Exit fullscreen mode
  • Create the folder(s) of your server and write the code for it.

  • Sample server code is,

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Part 4 - Install pm2

sudo npm i pm2 -g

pm2 start <server-file-name> --name "<process name>"
Enter fullscreen mode Exit fullscreen mode

Part 5 - Setup ufw firewall

sudo ufw enable

sudo ufw status

sudo ufw allow ssh (Port 22)

sudo ufw allow http (Port 80)

sudo ufw allow https (Port 443)
Enter fullscreen mode Exit fullscreen mode

Part 6 - Install NGINX and configure

sudo apt install nginx

sudo nano /etc/nginx/sites-available/default
Enter fullscreen mode Exit fullscreen mode
  • Sample server block looks like,
server {
    server_name <domain-name>;

    location / {
        proxy_pass http://localhost:<port of server>;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    listen 80;
}
Enter fullscreen mode Exit fullscreen mode
  • Add this to show default page for all the other URLs,
server {
    server_name <IPV4 address of the server>;
    root /var/www/html;
    index  index.nginx-debian.html;
    listen 80 default_server; 
}
Enter fullscreen mode Exit fullscreen mode
  • Check nginx config via,
sudo nginx -t
Enter fullscreen mode Exit fullscreen mode
  • Restart nginx via,
sudo service nginx restart
Enter fullscreen mode Exit fullscreen mode

Part 7 - Add SSL with Certbot

Top comments (0)