Autostart – How to run a service on Linux boot time using systemd

Autostart – How to run a service on Linux boot time using systemd

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.

Agenda
  1. Preparing service configuration file
  2. Enabling autostart and managing the newly created service
  3. Example: running docker container on Linux boot time

 

Preparing service configuration file

We start defining a new service by creating my-service.service file located in /etc/systemd/system directory:

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.

 

If the configuration presented above does not meet your expectations, I recommend you to read the official documentation of the systemd tool. You will find more advanced options there, which can solve your problem. If you are interested in this subject – I can discuss it in a separate post.

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:

 

Starting and stopping of the service:

 

Checking the status of the service

 

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:

with following content:

 

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.


 

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu