Systemd linux install centos

Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки.

Инструменты пользователя

Инструменты сайта

Боковая панель

Как создать свою службу (unit) в systemd на CentOS 7

Предположим, у нас есть веб-сервер Apache на базе CentOS 7, для которого настроено какое-то кастомное веб-приложение, требующее при загрузке системы предварительного прогревочного запуска. То есть, перед тем, как пользователи начали с ним работу, необходимо выполнить вызов какого-либо URL для того, чтобы при первом обращении к веб-приложению пользователи не испытывали задержек его отклика. Для решения этой задачи мы воспользуемся функционалом systemd и создадим свою службу (unit), которая будет выполнять прогревочную команду после запуска основной службы веб-сервера.

Создадим файл службы с любым удобным для нас именем, например webapp-warmup.

Наполним файл содержимым примерно следующего вида:

Пробуем выполнить запуск службы. Служба должна запуститься без ошибок:

Убедимся в том, что наша служба фигурирует в списке служб systemd:

Включаем автозагрузку службы при старте системы:

Перезагружаем сервер и убеждаемся в том, что в процессе запуска системы, после запуска служб httpd, успешно запускается наша прогревочная служба:

Автор первичной редакции:
Алексей Максимов
Время публикации: 03.10.2016 14:00

Источник

How to create and manage services in CentOS 7 with systemd

Systemd is a system and service manager and like most major Linux distributions the init deamon was replaced by systemd in CentOS 7. One of the main functions of systemd is to manage the services, devices, mount points, sockets and other entities in a Linux system. Each of these entity that are managed by systemd is called a unit. Each unit is defined by a unit file (configuration file) which is located in one of the following directories.

Directory Description
/usr/lib/systemd/system/ Unit files distributed with installed packages. Do not modify unit files in this location.
/run/systemd/system/ Unit files that are dynamically created at runtime. Changes in this directory are lost when rebooted.
/etc/systemd/system/ Unit files created by systemctl enable and custome unit files created by system administrators.

Any custom unit files that you create should be placed in the /etc/system/system/ directory. This directory takes precedence over other directories.

Unit files names are of the form

Unit_type can be one of the following:

Unit Type Description
device A device unit.
service A system service.
socket A socket for inter-process communication.
swap A swap file or device.
target A group of units.
timer A systemd timer.
snapshot A snapshot of systemd manager.
mount A mount point.
slice A group of unit that manage the system processes.
path A file or directory.
automount A automount point.
scope An externally created process.

Creating a new service (systemd unit)

To create a custom service to be managed by systemd , you create a unit file that defines the configuration of that service. To create a service named MyService for example, you create a file named MyService.service in /etc/systemd/system/

Читайте также:  Почему может не запускаться линукс с флешки

The unit file of service consists of a set of directives that are organized in to three sections — Unit, Service and Install. Below is an example of a very simple unit file.

Once you have created the unit file with all the necessary configuration options, save the file and set the correct file permissions.

The next step is to reload all unit files to make systemd know about the new service.

Finally to start the service, run

[Unit] Section

The following are the main directives that you specify in the [Unit] section.

Description A short description of the unit.
Documentation A list of URIs pointing to the documentation for the unit.
Requires A list of units that must be started alongside the current unit. If the any these units fail to start then current unit will not be activated.
Wants Similar to the Requires directive but the difference is the current unit will be activated even if the depended units fail to start.
Before List of units that cannot be started before the current unit.
After The current unit can started only after the units listed here.
Conflicts List units that cannot be run concurrently with the current unit.

[Service] Section

Some of the common directives that you’ll see in service section are.

Type Defines the startup type of the unit which can be one of the values:
  • Simple: This is the default. The main process of the service is the process started with ExecStart.
  • Forking: The process started with ExecStart spawns a new child process which becomes the main process and the parent process is terminated when the startup is completed.
  • Onehot: Similar to simple but systemd waits for the process to exit before proceeding with other units.
  • Dbus: Similar to simple but systemd waits for the process to take a name on the dbus.
  • Notify: Similar to simple Systemd will wait for a notification from the process before continuing with other units.
  • Idle: Similar to simple but service will not run until all other jobs are finished.
ExecStart Specifies the command to the executed to start service.
ExecStartPre Specifies the command to be executed before the main process specified in the ExecStart is started.
ExecStartPost Specifies the command to be executed after the main process specified in the ExecStart has finished.
ExecStop Specifies the command to be executed when the service is stopped.
ExecReload Specifies the command to be executed when the service is restarted.
Restart Specifies when to restart the service automatically. Possible values are «always», «on-success», «on-failure», «on-abnormal», «on-abort», or «on-watchdog».

[Install] Section

The [install] section provides information required to enable or disable the units using the systemctl command. The common options are:

RequiredBy A list of units that requires unit. A symbolic link of this unit is created in the .requires directory of the listed unit.
WantedBy Specifies a list of targets under which the service should be started. A symbolic link of this unit is created in the .wants directory of the listed target.

Using systemctl to manage services

systemctl is the command line tool you can use to control and manage services in systemd. Let’s now take a look at the some of the important systemctl commands for service management.

Listing Service Units and Unit files

To list all the units that are loaded

To list only units of type service

To list all installed unit files of type service

To list all installed unit files of type service

You can use the —state option to filter the output by the state of the unit. The following command lists all services that are enabled.

Note the difference between list-units and list-unit-files is that list-unit will only show units that are loaded while list-unit-files shows all unit files that are installed on the system.

Start and Stop service

This is quite straightforward, start option to start a service and stop option to stop a service

Restart and Reload services

The restart option will restart a service that is running. If the service is not running, it will be started.

If you want to restart the service only if its running then use the try-restart option.

The reload option will try to reload the service specific configuration of a unit if it is supported.

Enable and Disable services

Units can be enabled or disabled using the enable or disable options of systemctl command. When a unit a enabled symbolic links are created in various locations as specified in the [install] section of the unit file. Disabling a unit will remove the symbolic links that wer created when the unit was enabled.

Reload Unit Files

Whenever you make any changes to the unit files you need to let systemd know by executing daemon-reload which reloads all unit files.

Modifying system services

The unit files that come with installed packages are stored in /usr/lib/systemd/system/ . The unit files in this directory should not be modified directly as the changes will be lost when if you update the package. The recommended method is to first copy the unit file to /etc/systemd/system/ and make the changes in that location. The unit files in /etc/systemd/system/ takes precedence over unit files in /usr/lib/systemd/system/ so the original unit file will be overridden.

Источник

Systemd за пять минут

Наша компания занимается администрированием веб-серверов на базе CentOS. Довольно часто наши клиенты используют веб-приложения на базе python, ruby или java. Для автозапуска подобных приложений есть готовые шаблоны для написания стартап-скриптов. Но прогресс не стоит на месте, вышел уже второй релиз CentOS 7 и, следуя старой традиции «не ставить dot-zero релизы на продакшен», мы начинаем предлагать клиентам сервера на базе CentOS 7.1 (1503).

В CentOS7, так же как и в его родителе RHEL7, используется systemd — менеджер системы и служб для Linux, совместимый со скриптами инициализации SysV и LSB. systemd обеспечивает возможности агрессивной параллелизации и много всего прочего.

Огромный монстр с множеством возможностей, гибкими настройками и мегабайтами документации…

Но что делать, если стоит задача быстро-быстро, вот прямо вчера, сделать автозапуск некоего сервиса?
Давайте выжмем из документации минимально необходимый набор информации для создания простых старт-стоп скриптов.

Systemd запускает сервисы описанные в его конфигурации.
Конфигурация состоит из множества файлов, которые по-модному называют юнитами.

Все эти юниты разложены в трех каталогах:

/usr/lib/systemd/system/ – юниты из установленных пакетов RPM — всякие nginx, apache, mysql и прочее
/run/systemd/system/ — юниты, созданные в рантайме — тоже, наверное, нужная штука
/etc/systemd/system/ — юниты, созданные системным администратором — а вот сюда мы и положим свой юнит.

Юнит представляет из себя текстовый файл с форматом, похожим на файлы .ini Microsoft Windows.

[Название секции в квадратных скобках]
имя_переменной = значение

Для создания простейшего юнита надо описать три секции: [Unit], [Service], [Install]

В секции Unit описываем, что это за юнит:
Названия переменных достаточно говорящие:

Далее следует блок переменных, которые влияют на порядок загрузки сервисов:

Запускать юнит после какого-либо сервиса или группы сервисов (например network.target):

After=syslog.target
After=network.target
After=nginx.service
After=mysql.service

В итоге переменная Wants получается чисто описательной.
Если сервис есть в Requires, но нет в After, то наш сервис будет запущен параллельно с требуемым сервисом, а не после успешной загрузки требуемого сервиса

В секции Service указываем какими командами и под каким пользователем надо запускать сервис:

(по умолчанию): systemd предполагает, что служба будет запущена незамедлительно. Процесс при этом не должен разветвляться. Не используйте этот тип, если другие службы зависят от очередности при запуске данной службы.

systemd предполагает, что служба запускается однократно и процесс разветвляется с завершением родительского процесса. Данный тип используется для запуска классических демонов.

Также следует определить PIDFile=, чтобы systemd могла отслеживать основной процесс:

Команды на старт/стоп и релоад сервиса

ExecStart=/usr/local/bin/bundle exec service -C /work/www/myunit/shared/config/service.rb —daemon
ExecStop=/usr/local/bin/bundle exec service -S /work/www/myunit/shared/tmp/pids/service.state stop
ExecReload=/usr/local/bin/bundle exec service -S /work/www/myunit/shared/tmp/pids/service.state restart

Тут есть тонкость — systemd настаивает, чтобы команда указывала на конкретный исполняемый файл. Надо указывать полный путь.

Таймаут в секундах, сколько ждать system отработки старт/стоп команд.

Попросим systemd автоматически рестартовать наш сервис, если он вдруг перестанет работать.
Контроль ведется по наличию процесса из PID файла

В секции [Install] опишем, в каком уровне запуска должен стартовать сервис

multi-user.target или runlevel3.target соответствует нашему привычному runlevel=3 «Многопользовательский режим без графики. Пользователи, как правило, входят в систему при помощи множества консолей или через сеть»

Вот и готов простейший стартап скрипт, он же unit для systemd:
myunit.service

Кладем этот файл в каталог /etc/systemd/system/

Смотрим его статус systemctl status myunit

Видим, что он disabled — разрешаем его
systemctl enable myunit
systemctl -l status myunit

Если нет никаких ошибок в юните — то вывод будет вот такой:

Запускаем сервис
systemctl start myunit

Смотрим красивый статус:
systemctl -l status myunit

Если есть ошибки — читаем вывод в статусе, исправляем, не забываем после исправлений в юните перегружать демон systemd

Источник

Читайте также:  Не могу зайти безопасный режим windows 10 если система не загружается
Оцените статью