uniq_

host docker container via systemd on debian 8

I want to run a custom docker image as a systemd service. This assumes I'm starting out on plain debian 8:

# add backports repository
sudo bash -c 'echo -e "\\n\\n#backports\\ndeb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list'

# install docker
sudo apt-get update
sudo apt-get install docker.io

# optional: add your user to docker group so you dont
# have to use sudo all the time for calling docker
# (you will need to log in again to make this come into effect.
# or simply start a new shell)
#sudo adduser $USER docker

# tell systemd to start docker on boot
sudo systemctl enable docker


# create docker container
# (just a simple test container, you might create your own...)
sudo docker run -d -p 80:80 --name example_webserver nginx

## create a systemd unit for a docker container
## (repeat this step for every container you need)

cat << EOF | sudo bash -c 'cat >> /etc/systemd/system/docker-example_webserver.service'

[Unit]
Description=Test Web Server
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker start -a example_webserver
ExecStop=/usr/bin/docker stop -t 2 example_webserver

[Install]
WantedBy=default.target

EOF

# reload systemd because we added a new unit
sudo systemctl daemon-reload

# start docker container
sudo systemctl start docker-example_webserver.service

# tell systemd to start docker container on boot
sudo systemctl enable docker-example_webserver.service

resources:

written by uniq on 2016-08-22