Look at LSB init scripts for more information.
Copy to /etc/init.d
:
# replace "$YOUR_SERVICE_NAME" with your service's name (whenever it's not enough obvious)
cp "service.sh" "/etc/init.d/$YOUR_SERVICE_NAME"
chmod +x /etc/init.d/$YOUR_SERVICE_NAME
Edit the script and replace following tokens:
<NAME>
=$YOUR_SERVICE_NAME
<DESCRIPTION>
= Describe your service here (be concise)- Feel free to modify the LSB header, I've made default choices you may not agree with
<COMMAND>
= Command to start your server (for example/home/myuser/.dropbox-dist/dropboxd
)<USER>
= Login of the system user the script should be run as (for examplemyuser
)
Start and test your service:
service $YOUR_SERVICE_NAME start
service $YOUR_SERVICE_NAME stop
Install service to be run at boot-time:
update-rc.d $YOUR_SERVICE_NAME defaults
Enjoy
The service can uninstall itself with service $NAME uninstall
. Yes, that's very easy, therefore a bit dangerous. But as it's an auto-generated script, you can bring it back very easily. I use it for tests and often install/uninstall, that's why I've put that here.
Don't want it? Remove lines 56-58 of the service's script.
Your service will log its output to /var/log/$NAME.log
. Don't forget to setup a logrotate :)
Yep, I'm lazy too. But still, I've written a script to automate this :)
wget 'https://raw.github.com/gist/4275302/new-service.sh' && bash new-service.sh
In this script I will download service.sh
into a tempfile
, replace some tokens, and then show you commands you should run as superuser.
If you feel confident enough with my script, you can sudo
the script directly:
wget 'https://raw.github.com/gist/4275302/new-service.sh' && sudo bash new-service.sh
Note: the cool hipsterish curl $URL | bash
won't work here, I don't really want to check why.
Creating the service:
Looking at service files (logs, pid):
Uninstalling service:
I had a couple issues with the "start" function above on Ubuntu 16.04 LTS.
For one it references a made up variable like @fengye mentioned above. His fix works for me:
if [ -f "$PIDFILE" ] && kill -0 $(cat "$PIDFILE"); then
For me output of the script was going into the pid file and not the log file which prevented it from shutting down and also was dumb. Had to do this.
su -c "$CMD" $RUNAS > "$LOGFILE"
The trickiest issue I ran into was with writing the process id to the file. I think it may be because my script uses xonsh and there's a slight delay starting up. I'm not sure, but I found that I had to use the double ampersand here or the pid written to the file would be wrong.
local CMD="$SCRIPT &> \"$LOGFILE\" && echo \$! > $PIDFILE"
Here's the whole function for convenience: