Infinite | Squares

Art of code and more

Nginx for Node.js

Nginx is a high performance web server. Some said it is better than Apache. Nginx can be used as reverse proxy for Node.js server application. And also as static file server since it’s very efficient. If you are have a VPS or VM running, you can use Nginx as front for more than one Node.js app.

First, you have to install Nginx first. My standard script for installing development server is available here. Once you have nginx setup, when you access your server on port 80, you will see nginx welcoming screen.

Here, I assume you already have a Nodejs app running. Use forever or pm2 for production server.

Remove the default site file. You can choose to keep this, just make sure the server_name is different.

1
2
sudo rm /etc/nginx/sites-available/default
sudo rm /etc/nginx/sites-enabled/default

Create new file for your site

1
sudo nano /etc/nginx/sites-available/mysite

The content

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
upstream myNodeApp{
    server localhost:4000;
}

server{
    server_name localhost;

    access_log /home/server/logs/access.log;
    error_log /home/server/logs/access.log;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://myNodeApp;
        proxy_redirect off;
    }
}

Save and close the nano text editor. Make sure you have created logs folder as shown above.

Then create a symbolic link from sites-available to sites-enabled

1
sudo ln –s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/mysite

Check your site file

1
sudo nginx -t

If there are error, nginx will tell you.

Restart nginx

1
sudo service nginx restart

Access your server on port 80 using your favorite browser. There is your nodejs app.

Comments