Using systemd to start Docker containers


You want to automatically start Docker containers at boot and/or you wish to give your system administrators a familiar way to start and stop Docker containers using the systemctl command.


You have a Docker container running with a unique name (i.e. my-web-server).

# docker run -d --name my-web-server --restart-always -p 80:80 -v /mnt/my-web-server-logs:/var/logs rhscl/httpd-24-rhel7

Step #1

Create a system service unit file as root in the "/etc/systemd/system" directory.

# vi /etc/systemd/system/docker-my-web-server.service

Add the following contents to the "docker-my-web-server.service" unit file.

Description=My Web Server Docker Container

ExecStart=/usr/bin/docker start -a my-web-server
ExecStop=/usr/bin/docker stop -t 2 my-web-server


Step #2

Change the permissions of the unit file.

# chmod 664 /etc/systemd/system/docker-my-web-server.service

Step #3

Reload systemd.

# systemctl daemon-reload

Step #4

Enable new service to start at boot.

# systemctl enable docker-my-web-server.service

Start/Stop new service using systemctl

# systemctl stop docker-my-web-server.service
# systemctl start docker-my-web-server.service

For additional information on using systemd to start and stop Docker containers, visit Red Hat's documentation regarding Creating Custom Unit Files or Docker's documentation Automatically start containers.