Tuesday, August 26, 2008

Setting up Glassfish to run as a service on Ubuntu

In order to do this a script needs be created and put into the /etc/init.d folder of the server. I copied this script from Cay Horstmann's Blog and made one or two changes. The main one being that I can spcify the domain to startup.

My script looks like this:

#!/bin/sh -e
### BEGIN INIT INFO
# Provides: glassfish
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: glassfish initscript
# Description: A simple initscript for the glassfish app server
### END INIT INFO
#
# Author: Cay S. Horstmann (http://horstmann.com)
#

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/glassfish/bin
DESC="Glassfish Java EE5 App Server"
NAME=glassfish
ASADMIN=asadmin
DOMAIN=dev
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

# Read config file if it is present.
#if [ -r /etc/default/$NAME ]
#then
# . /etc/default/$NAME
#fi

#
# Function that starts the daemon/service.
#
d_start() {
$ASADMIN start-domain $DOMAIN \
|| echo -n " already running"
}

#
# Function that stops the daemon/service.
#
d_stop() {
$ASADMIN stop-domain $DOMAIN \
|| echo -n " not running"
}

case "$1" in
start)
echo -n "Starting $DESC: $NAME [$DOMAIN]"
d_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME [$DOMAIN]"
d_stop
echo "."
;;
reload|restart|force-reload)
echo -n "Restarting $DESC: $NAME [$DOMAIN]"
d_stop
sleep 10
d_start
echo "."
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
exit 3
;;
esac

exit 0

You will need to decide on a service name (e.g. myglassfishservice) and then create a file with that name in the /etc/init.d folder.

cd /etc/init.d
sudo vi myglassfishservice


Paste the above script into the file. Check that the PATH variable points to the correct glassfish home folder and that the DOMAIN variable is the correct glassfish domain name. Then save the file.

Now setup the run groups by running the following command

sudo update-rc.d myglassfishservice defaults

This adds the symbolic links to your service in the folders /etc/rc0.d, /etc/rc1.d, ...

Now reboot the server and your specified domain on glassfish shold start

1 comment:

Robert Chifamba said...

interesting... one small addition though, there is no need to reboot the entire server, you can just start/restart the service. Normally something like
sudo /etc/init.d/myglassfishservice restart