Turning our simple code into a service using Upstart
Since we started the node application manually in the terminal, closing the ssh connection or hitting Ctrl + C on the keyboard will stop the node process, and therefore our Hello World application will not work anymore.
Amazon Linux, unlike standard Red Hat-based distributions, comes with a system called Upstart.
It is fairly easy to use and provides a couple of extra features that traditional System V bootup scripts don't have, such as the ability to respawn a process that died unexpectedly. To add an Upstart configuration, you need to create a file inside /etc/init on the EC2 instance.
Here is the code to insert in /etc/init/helloworld.conf:
description "Hello world Deamon"
# Start when the system is ready to do networking.
start on started elastic-network-interfaces
# Stop when the system is on its way down.
stop on shutdown
respawn
script
exec su --session-command="/usr/bin/node /home/ec2-user/helloworld.js" ec2-user
end script
Why to start on elastic-network-interfaces
If you are familiar with Upstart outside of AWS, you might have used start on runlevel [345]. The problem with that in AWS is that your network comes from Elastic Network Interface ( ENI), and if your application starts before this service, it might not be able to connect to the network correctly.