In this blog post, i will share my experiences on setting up NodeJS on EC2 server and various configuration settings involved. The Nodejs script will start automatically on server start up and run forever.
I am assuming you are familiar with the basic setting up an ec2 and starting an instance so won’t describe the basic. So lets get right to it
Choosing an AMI
The first step is to choose an AMI, you can go with the a standard 64bit ubuntu based AMI (install nodejs and applications on top if), but i went with a pre-build nodejs AMI by bitnami https://bitnami.com/stack/nodejs
In most of the cases, it would be a requirement that when you start a new ec2 instance some scripts should start up automatically or maybe some server should start listening on a port etc. This is achieved using upstart in ubuntu. Upstart is basically set of scripts which you can write to start on server startup and on different run levels, more details here.
So if you have a requirement where you want to start a nodejs script on server startup, you need to use upstart.
Here is a script which i used
start on runlevel  stop on runlevel  respawn respawn limit 99 5 #respawn is used to start the nodejs again, even if it fails. env NODE_ENV=development #script to start before actual script, pre script pre-start script cd /home/etech/public_html/pricegenie.in/ #directory where my script is present exec /usr/bin/sudo /usr/bin/git pull -u origin master #so that i get latest version of my code always end script script #export HOME="/home/bitnami" exec /usr/bin/sudo /opt/bitnami/nodejs/bin/node /home/etech/public_html/pricegenie.in/node/category.js letsdance >> /var/log/pg.log 2>&1 end script
Please the above code in /etc/init/node.conf file
The above script starts when my ec2 start is started fully and make sure nodejs script keeps on running. I don’t need to use “forever” here, since i am using respawn which has the same effect.
To test if the script runs
sudo start node
This should return “node start/running, process 1211” on success
sudo stop node
This should return “node stop/waiting” on success.
You can also see log files for upstart at /var/log/upstart/node.log and for your script at /var/log/pg.log