Linux create systemd service

Systemd: Service File Examples

Most Linux distributions use systemd as a system and service manager.

The systemctl is the main command in systemd, used to control services.

In this tutorial i will show how to create a systemd service file that will allow you to control your service using the systemctl command, how to restart systemd without reboot to reload unit files and how to enable your new service.

I will also show and describe the most important systemd service file options with the live examples of the systemd service files.

Create Systemd Service File

Create a systemd service file /etc/systemd/system/foo-daemon.service (replace the foo-daemon with your service name):

$ sudo touch /etc/systemd/system/foo-daemon.service $ sudo chmod 664 /etc/systemd/system/foo-daemon.service

Open the foo-daemon.service file and add the minimal service configuration options that allow this service to be controlled via systemctl :

[Unit] Description=Foo [Service] ExecStart=/usr/sbin/foo-daemon [Install] WantedBy=multi-user.target

Path To Daemon : If you don’t know the full path to a daemon, try which foo-daemon .

Once the service file is changed, it needs to reload systemd configuration:

$ sudo systemctl daemon-reload

Now you should be able to start , stop , restart and check the service status

$ sudo systemctl start foo-daemon $ sudo systemctl stop foo-daemon $ sudo systemctl restart foo-daemon $ systemctl status foo-daemon

To configure a service to start automatically on boot, you need to enable it:

$ sudo systemctl enable foo-daemon

To check the service logs, run:

Systemd Service File Options

The common configuration items are configured in the generic [Unit] and [Install] sections.

The service specific configuration options are configured in the [Service] section.

Important [Unit] Section Options

Option Description
Description A short description of the unit.
Documentation A list of URIs referencing documentation.
Before , After The order in which units are started.
Requires If this unit gets activated, the units listed here will be activated as well. If one of the other units gets deactivated or fails, this unit will be deactivated.
Wants Configures weaker dependencies than Requires . If any of the listed units does not start successfully, it has no impact on the unit activation. This is the recommended way to establish custom unit dependencies.
Conflicts If a unit has a Conflicts setting on another unit, starting the former will stop the latter and vice versa.
Читайте также:  Linux все консольные команды

A complete list of [Unit] section options:

Important [Install] Section Options

Option Description
Alias A space-separated list of additional names for the unit. Most systemctl commands, excluding systemctl enable , can use aliases instead of the actual unit name.
RequiredBy , WantedBy The current service will be started when the listed services are started. See the description of Wants and Requires in the [Unit] section for details.
Also Specifies a list of units to be enabled or disabled along with this unit when a user runs systemctl enable or systemctl disable .

A complete list of [Install] section options:

Important [Service] Section Options

Option Description
Type Configures the process start-up type. One of:
simple (default) – starts the service immediately. It is expected that the main process of the service is defined in ExecStart .
forking – considers the service started up once the process forks and the parent has exited.
oneshot – similar to simple , but it is expected that the process has to exit before systemd starts follow-up units (useful for scripts that do a single job and then exit). You may want to set RemainAfterExit=yes as well so that systemd still considers the service as active after the process has exited.
dbus – similar to simple , but considers the service started up when the main process gains a D-Bus name.
notify – similar to simple , but considers the service started up only after it sends a special signal to systemd.
idle – similar to simple , but the actual execution of the service binary is delayed until all jobs are finished.
ExecStart Commands with arguments to execute when the service is started. Type=oneshot enables specifying multiple custom commands that are then executed sequentially. ExecStartPre and ExecStartPost specify custom commands to be executed before and after ExecStart .
ExecStop Commands to execute to stop the service started via ExecStart .
ExecReload Commands to execute to trigger a configuration reload in the service.
Restart With this option enabled, the service shall be restarted when the service process exits, is killed, or a timeout is reached with the exception of a normal stop by the systemctl stop command.
RemainAfterExit If set to True , the service is considered active even when all its processes exited. Useful with Type=oneshot . Default value is False .

A complete list of [Service] section options:

Читайте также:  Ubuntu rdp windows linux

Systemd Service File Examples

[Unit] Description=The NGINX HTTP and reverse proxy server After=syslog.target network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t ExecStart=/usr/sbin/nginx ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s QUIT $MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target
[Unit] Description=The Apache HTTP Server After=network.target remote-fs.target nss-lookup.target [Service] Type=notify EnvironmentFile=/etc/sysconfig/httpd ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND ExecReload=/usr/sbin/httpd $OPTIONS -k graceful ExecStop=/bin/kill -WINCH $ KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target
[Unit] Description=Redis persistent key-value database After=network.target [Service] ExecStart=/usr/bin/redis-server /etc/redis.conf --daemonize no ExecStop=/usr/bin/redis-shutdown User=redis Group=redis [Install] WantedBy=multi-user.target

For more examples, check the systemd.service and systemd.unit man pages.

Источник

How to Create a Systemd Service in Linux

Systemd is a modern software suite that provides many components on a Linux system including a system and service manager. It is compatible with SysV and LSB init scripts and works as a replacement for sysvinit.

A systemd service is defined in a unit file (a unit is a representation of a service and system resources such as devices, sockets, mount points, etc.). Custom service unit files should be stored in the /etc/systemd/system/ directory and must have an .service extension. For example, a custom test-app service uses /etc/systemd/system/test-app.service unit file.

A unit file is a plain text ini-style file that usually includes three common sections. The first section is usually the Unit section which carries generic information about the unit that is not dependent on the type of unit.

The next section is the unit type section, for a service, it is a Service section. And the final section is the Install section which carries installation information for the unit.

In this guide, we will show how to create a new systemd service and manage the service using the systemctl command, in Linux.

Creating Custom Systemd Service File in Linux

To run an application or program or script as a service under systemd, you can create a new systemd service as follows. Start by creating the service unit file named test-app.service (remember to replace test-app with the actual name of your service or application), under /etc/systemd/system/:

# vi /etc/systemd/system/test-app.service

The following configuration is used to define a service for running a Flask application using Gunicorn, a Python WSGI HTTP Server for UNIX.

[Unit] Description=Gunicorn daemon for serving test-app After=network.target [Service] User=root Group=root WorkingDirectory=/apps/test-app/ Environment="PATH=/apps/test-app/bin" ExecStart=/apps/test-app/bin/gunicorn --workers 9 -t 0 --bind 127.0.0.1:5001 -m 007 wsgi:app --log-level debug --access-logfile /var/log/gunicorn/test_app_access.log --error-logfile /var/log/gunicorn/test_app_error.log ExecReload=/bin/kill -s HUP $MAINPID RestartSec=5 [Install] WantedBy=multi-user.target

Let’s briefly describe each configuration directive in the configuration above:

  • Description – is used to specify a description for the service.
  • After – defines a relationship with a second unit, the network.target. In this case, the test-app.service is activated after the network.target unit.
  • User – is used to specifying the user with whose permissions the service will run.
  • Group – is used to specify the group with whose permissions the service will run.
  • WorkingDirectory – is used to set the working directory for executed processes.
  • Environment – is used to set environment variables for executed processes.
  • ExecStart – is used to define the commands with their arguments that are executed when this service is started.
  • ExecReload – is used to define the commands to execute to trigger a configuration reload in the service.
  • WantedBy – enables a symbolic link to be created in the .wants/ or .requires/ directory of each of the listed unit(s), multi-user.target in this case, when the test-app.service unit is enabled using the systemctl enable command.
Читайте также:  Linux command to display all files

You can find all service unit configuration parameters, well described in the Service unit configuration documentation.

Save the unit file and close it. Then reload systemd with this new service unit file by running:

# systemctl daemon-reload command

Remember to always run this command after editing a unit file.

Manage Systemd Service in Linux

To start/activate the service, run the systemctl command as follows:

# systemctl start test-app.service

To check if the service is running or not, issue the systemctl command as shown.

# systemctl status test-app.service

Check Status of Service

To enable the service to start at system boot, use the systemctl enable command. You can check if the service has been enabled using the systemctl is-enable command as follows:

# systemctl enable test-app.service # systemctl is-enabled test-app.service

Enable Service to Start at Boot

Alternatively, you can also enable and start the service at the same time as shown.

# systemctl enable --now test-app.service

To stop/deactivate the service, run the systemctl stop command as follows:

# systemctl stop test-app.service

To restart the service, run the systemctl restart command as follows:

# systemctl restart test-app.service

You can also disable a service to prevent it from starting at system boot, using the systemctl disable command. You can check if the service has been enabled using the systemctl is-enable command as follows:

# systemctl disable test-app.service # systemctl is-disabled test-app.service

Alternatively, you can disable and stop it at the same time as shown.

# systemctl disable --now test-app.service

For more details about managing systemd services and other resources, run:

Источник

Оцените статью
Adblock
detector