Skip to content

writing an init.d script for a docker container

Tony Woode edited this page Apr 8, 2015 · 1 revision

This describes a simple init.d script for running a single instance of a docker container.

First, dockerise your component. Then make a copy of the script below - call it init.d, create it next to your Dockerfile. Change references to logger to your component. Adjust the INIT INFO block to taste. Set NAME to the name you specified when building the docker container (docker build -t $NAME .) and CONTAINER_OPTS to any runtime parameters like port mappings or external colume specifications.

#!/bin/bash
#!/bin/bash
### BEGIN INIT INFO
# Provides:          logger
# Required-Start:    $syslog $remote_fs docker
# Required-Stop:     $syslog $remote_fs docker
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Logger
# Description:       OpenShare logger component
### END INIT INFO

NAME=logger
CONTAINER_OPTS="--env AMQP_HOST=192.168.1.27 -v /var/log:/var/log"

# Source function library.
. /lib/lsb/init-functions

start() {
        echo -n "Starting dokcer container $NAME: "
        /usr/bin/docker rm $NAME 2>/dev/null
        /usr/bin/docker run --name=$NAME -d $CONTAINER_OPTS $NAME
        RETVAL=$?
        touch /var/lock/$NAME
        return $RETVAL
}

stop() {
        echo -n "Shutting down $NAME: "
        /usr/bin/docker kill $NAME
        RETVAL=$?
        rm -f /var/lock/$NAME
        return $RETVAL
}

status() {
        echo -n "Checking $NAME status: "
        /usr/bin/docker top $NAME 
        RETVAL=$?
        return $RETVAL
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        stop
        start
        ;;
    reload)
        stop
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|status|reload|restart[|probe]}"
        exit 1
        ;;
esac
exit $?

You can then install with the commands below (change logger to whatever your component is called) - either run the cp and update-rc.d commands directly or add to your build process:

install:
	cp init.d /etc/init.d/logger
	update-rc.d logger defaults
Clone this wiki locally