Docker RUN with Systemd

Cindy Piassale29/07/2020


The use of containers (docker or other), for the installation of software in a company, can seem obscure for system administrators.

To simplify the use of docker containers , systemd is an alternative to docker-compose.

Principle

The general idea is to define each container as a systemd service. So the administrator uses the standard linux systemctl commands to manage his applications.

In addition we benefit from the management of services (automatic start-up, dependencies, etc.) natively managed by systemd.

Implementation

Example with a very simple blogging service : ghost.

In the / etc / systemd / system folder, we create a file corresponding to our service.

#/etc/systemd/system/ghost.service

[Unit]
Description=Docker container
BindsTo=docker.service
After=docker.service

[Service]
Restart=on-failure
RestartSec=10
ExecStartPre=-/usr/bin/docker kill ghost
ExecStartPre=-/usr/bin/docker rm ghost
ExecStart=/usr/bin/docker run --name ghost \
    -v "/var/ghost/data:/var/lib/ghost/content" \
    -e "url=http://localhost:8080" \
    -p 8080:2368 \
    ghost
ExecStop=/usr/bin/docker stop ghost

[Install]
WantedBy=multi-user.target

To be able to start this service, it is necessary to install docker and create the / var / ghost / data folder that we defined as a linked volume and which will receive the blog data.

Example with Centos 7 :

sudo yum install yum-utils -y
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install docker-ce
sudo mkdir -p /var/ghost/data

Usage

This service can be used like any other service with the usual commands :

systemctl start|restart|stop|status ghost

Once the service is started, the instance ghost that we just launched will be available at http://localhost:8080

Logs

The consulation of logs can be made thanks to the command journalctl. To view the logs of a single container you can do the following command :

journalctl -u <container_name>

Example with ghost application :

journalctl -u ghost

We have a more specific article on the managment of logs in containers


A propos de JECI

Maintenance Logicielle, Conteneur (Docker, Kubernetes), Alfresco Community, Logiciels Libres
SARL - Capital : 100 000 €, immatriculée au RCS de Dijon

Nous contacter

+33 9 72 38 21 92 info@jeci.fr

2013-2020 Jeci | Mixed with v4.3.2 | Baked with JBake v2.6.4 | Photo by Valdas Miskinis on Unsplash | Mentions légales