jjk2sfu
By:
jjk2sfu

Automatically launch bash script on droplet creation?

May 13, 2014 3.9k views
Basically, I have an image with a flask server. When I create a new droplet from it, the flask server doesn't run. It needs to be manually run. How can I make the bash script to run `python server.py` as soon as the droplet is ready instead of me having to manually ssh in or run fabric?
2 Answers
The best way to have something run on boot is use an init script. Assuming you are using Ubuntu, you can use Upstart to write it in a simple declarative format. A quick example might look like:


description "Daemon for flask project"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectedly trigger a respawn
respawn

setuid myuser
setgid mygroup
chdir /path/to/dir

exec uwsgi --master \
--processes 4 \
--die-on-term \
--socket /tmp/uwsgi.sock


Save the file to "/etc/init/myservice.conf" It will now launch on boot once the filesystem is mounted and the network is active. You can also manage it like other services, using:


service myservice start
service myservice restart
service myservice stop

@asb : stop on runlevel [!12345] --> is that mean any runlevel except {1, 2, 3, 4, 5}

Have another answer? Share your knowledge.