Effective DevOps with AWS
上QQ阅读APP看书,第一时间看更新

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.
[ec2-user@ip-172-31-22-234 ~]$ sudo wget http://bit.ly/2vVvT18 -O /etc/init/helloworld.conf
--2017-02-01 00:20:03--  http://bit.ly/2vVvT18
Resolving bit.ly (bit.ly)... 69.58.188.39, 69.58.188.40
Connecting to bit.ly (bit.ly)|69.58.188.39|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://raw.githubusercontent.com/EffectiveDevOpsWithAWS/code-snippets/master/helloworld.conf [following]
--2017-02-01 00:20:03--  https://raw.githubusercontent.com/EffectiveDevOpsWithAWS/code-snippets/master/helloworld.conf
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 199.27.76.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|199.27.76.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 286 [text/plain]
Saving to: '/etc/init/helloworld.conf'
    
/etc/init/helloworld.conf         100%[=============================================================>]     286  --.-KB/s   in 0s
    
2017-02-01 00:20:03 (67.4 MB/s) - '/etc/init/helloworld.conf' saved [286/286]
    
[ec2-user@ip-172-31-22-234 ~]$  

We can now simply start our application, as follows:

[ec2-user@ip-172-31-22-234 ~]$ sudo start helloworld
helloworld start/running, process 23090
[ec2-user@ip-172-31-22-234 ~]$  

As expected, http://your-public-dns-name:3000 still works, and this time, we can safely close our ssh connection.