I recently had the need to run one of the Docker containers during the start of the Linux operating system. I decided to share with you the fastest, and the easiest way I have found so far to start any service in Linux – by using the systemd tool.
- Preparing service configuration file
- Enabling autostart and managing the newly created service
- Example: running docker container on Linux boot time
1. Preparing service configuration file
We start defining a new service by creating my-service.service file located in /etc/systemd/system directory:
sudo nano /etc/systemd/system/my-service.service
The following listing presents the simplest configuration, which is required to run the service. As you can see it is very simple. We put only the name of the service and commands responsible for to starting and stopping our service.
[Unit] Description=My Service [Service] ExecStart=/path/to/my/service start ExecStop=/path/to/my/service stop [Install] WantedBy=default.target
2. Enabling autostart and managing the newly created service
Simply placing the service configuration in the /etc/systemd/system directory it is not enough service to be launched at system startup. To achieve this effect, we have to activate the service. The following listings present some commands that are responsible for activating, deactivating, manual starting and stopping and checking the current status of the service.
Activation and deactivation of service run during system startup:
sudo systemctl enable my-service.service sudo systemctl disable my-service.service
Starting and stopping of the service:
sudo systemctl start my-service.service sudo systemctl stop my-service.service
Checking the status of the service
systemctl status my-service.service
3. Example: running docker container on Linux boot time
It is the time to discuss the theory presented above on a specific example. Let this be the launch of the Docker container named my-container-name. Let is assume that our service is called my-docker-service. Based on the previously presented theory, create the file my-docker-service.service:
sudo nano /etc/systemd/system/my-docker-service.service
with following content:
[Unit] Description=My Docker container Requires=docker.service After=docker.service [Service] Restart=always ExecStart=/usr/bin/docker start -a my-container-name ExecStop=/usr/bin/docker stop -t 10 my-container-name [Install] WantedBy=default.target
The last step is to activate the service run during system startup. To check the correctness of the configuration, we can manually start our service and check its status.
sudo systemctl enable my-docker-service.service sudo systemctl start my-docker-service.service sudo systemctl status my-docker-service.service