How to setup Node.js application server with port 80 

Port 80

Redirect port 80 to port 3000 with this command:

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

Then launch the Node.js application on port 3000. Now requests to port 80 will map to the nodejs application on port 3000. Edit the /etc/rc.local file and adding iptables port redirection line (without ‘sudo’). This step with cause the port redirect when the machine boots up. Commands in /etc/rc.local are run as root as the system boots.
example :

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

#forward port 80 to port 3000 for node Server
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

#Auto start node server on reboot
nodejs /home//path/to/node/app.js

exit 0

Logs

Use the forever module for launching your NodeJS application. Forever will make sure that your application restarts if it ever crashes. In addition, it will redirect console logs to a specified file.

Launch on Boot

IN the same way you added the port redirection command in the file, /etc/rc.local, edit the same file and add the node application start command to the file. When the system starts, the port redirection command will execute and then the application start line will execute. See above example.

Cloud Machines

This will work on AWS EC2, Digital Ocean, and others VPS providers. Note that on RedHat based systems /etc/rc.local has a different filename, /ect/rc.d/local.

Leave a Reply

Your email address will not be published.