Управление сервисами в Linux. Команда systemctl
Сервисы или службы — это программы, которые работают в системе Linux в фоновом режиме. Обычно они запускаются при загрузке системы. Большинство сервисов необходимы для полноценной работы системы, то есть они являются своего рода кирпичиками, из которых строится работающая система.
При запуске системы загружается целый ряд сервисов, которые включены для автозагрузки. Сервисы работают пока система запущена, и выгружаются при выключении системы.
Чаще всего в Linux дистрибутивах для инициализации сервисов используется демон Systemd. К Systemd-дистрибутивам относятся Ubuntu, Debian, Linux Mint, Fedora, openSUSE, Solus и другие.
Есть дистрибутивы, которые не используют Systemd. Вместо Systemd могут использоваться такие системы инициализации, как Upstart, SysV.
В качестве примеров сервисов можно привести: веб-сервер Apache, Network Manager, файрвол Ufw и другие.
Для управления сервисами (Systemd) используется утилита systemctl . Ниже мы рассмотрим основные команды данной утилиты.
Список сервисов
Чтобы просмотреть список всех сервисов можно воспользоваться командой:
Данная команда пробегает по алфавитному списку всех доступных сервисов и выполняет для них команду status.
В выводе команды используются следующие обозначения:
- [ + ] — запущенный сервис.
- [ — ] — остановленный сервис.
- [ ? ] — для данного сервиса отсутствует команда status.
Запуск сервиса
Для запуска сервиса используется команда systemctl start имя_сервиса
Останов сервиса
Для остановки сервиса используется команда systemctl stop имя_сервиса
Перезапуск сервиса
Перезапуск сервиса выполняется командой systemctl restart имя_сервиса
sudo systemctl restart ufw
Обычно перезапуск конкретного сервиса требуется, когда были изменены настройки данного сервиса.
Некоторые сервисы поддерживают «мягкую» перезагрузку. В этом случае сервис считывает связанные с ним файлы конфигурации, но не прерывает процесс сервиса. Для выполнения «мягкой» перезагрузки используется команда systemctl reload имя_сервиса . Не все сервисы поддерживают «мягкую» перезагрузку. Если она не поддерживается, то появится сообщение вида: Failed to reload ufw.service: Job type reload is not applicable for unit ufw.service.
Автозагрузка сервисов
Чтобы сервис стартовал (загружался) при запуске системы, его нужно включить в список автозагрузки. Для этого используется команда systemctl enable имя_сервиса
sudo systemctl enable ufw Synchronizing state of ufw.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable ufw
Чтобы включить сервис в автозапуск и сразу же запустить используется команда:
Чтобы удалить сервис из автозагрузки, используется команда systemctl disable имя_сервиса
sudo systemctl disable ufw
Статус сервиса
Для вывода информации (статуса) сервиса используется команда systemctl status имя_сервиса
Чтобы проверить, запущен ли в данный момент сервис, используется команда systemctl is-active имя_сервиса
systemctl is-active ufw acive
Чтобы проверить, включен ли сервис для автозапуска при загрузке системы, используется команда systemctl is-enabled имя_сервиса
systemctl is-enabled ufw enabled
Заключение
Мы рассмотрели наиболее часто используемые команды утилиты systemctl. Полный список команд и опций утилиты systemctl можно получить, выполнив:
How to Remove Service in Linux
Sometimes you may want to remove the Systemd service or at least make it unavailable for use. There is no sense to remove the unit file, cause after the next system update this file may be recovered.
The simplest way to remove a service in Linux — remove the package which provides this service. First, find the path to the unit file. You can use the systemctl status command:
sudo systemctl status nginx
Then, you can use the dpkg command to find a package which owns the file if you use Ubuntu. For example:
dpkg -S /lib/systemd/system/nginx.service
After this, you can remove the package:
If you don’t want to delete the package or it is impossible, cause the service is provided by one of the system packages, you can mask the service. Systemd wouldn’t start masked packages on the system startup even if they are added to the system autostart. And, of course, you can’t start them manually. Use the mask command to make the package unavailable. For example:
sudo systemctl mask nginx
After this, you can check the status of the service and ensure that it has been masked:
sudo systemctl status nginx
Also, you will get an error when trying to start the service:
sudo systemctl start nginx
Use the unmask command to disable masking and make the service available for using:
sudo systemctl unmask nginx
Now, you have learned how to remove service in Linux. As you can see it is pretty straightforward. Read about services in detail in this article.
Found a mistake in the text? Let me know about that. Highlight the text with the mistake and press Ctrl+Enter.
How to remove systemd services
If I install a new service then decide I don’t want that application anymore and delete it, the service is still listed in the output from systemctl as error. Where is this coming from and how can I remove them thoroughly?
7 Answers 7
My recipe for service obliteration (be careful with the rm statements!)
systemctl stop [servicename] systemctl disable [servicename] rm /etc/systemd/system/[servicename] rm /etc/systemd/system/[servicename] # and symlinks that might be related rm /usr/lib/systemd/system/[servicename] rm /usr/lib/systemd/system/[servicename] # and symlinks that might be related systemctl daemon-reload systemctl reset-failed
It is possible that the systemd service ‘wraps’ the old style scripts in /etc/init.d, so you may want to clean that up too, but that is not where systemd services live.
Be aware that there are multiple locations where Systemd unit files are stored, notably /usr/lib/systemd/system and also /etc/systemd/system/ . For reference see: access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/…
Right, I forgot to disable before removing the unit files. BTW, to find all unit files to remove, I inspect the output of systemctl cat [servicename] .
You are probably looking for reset-failed :
$ sudo systemctl reset-failed $
From the systemd man page:
reset-failed [PATTERN. ]
Reset the «failed» state of the specified units, or if no unit name is passed, reset the state of all units. When a unit fails in some way (i.e. process exiting with non-zero error code, terminating abnormally or timing out), it will automatically enter the «failed» state and its exit code and status is recorded for introspection by the administrator until the service is restarted or reset with this command.
This is the only correct answer. The other ones with more upvotes and the check mark are workarounds.
This was exactly what I needed. The service apparently was removed, but the failed state was still kicking around.
It sounds like this just resets the state for a service that should no longer exist. You should very likely delete the service files themselves, not simply change the state of a service you no longer want.
Sounds like you uninstalled it, but didn’t remove the systemd hook:
# systemctl disable [servicename]
Adding on to @mark-lakata’s answer and keeping in mind the attentiveness required for the rm command. [chkconfig] can simplify the process!(click here to read about chkconfig)
To re-iterate the list of commands:
- systemctl stop [servicename]
- chkconfig [servicename] off OR for newer systems systemctl disable [servicename]
- systemctl daemon-reload
- systemctl reset-failed
Note: The 1st command is optional depending on whether you want keep the service running in the present session or not (as for this question the command should be used).
The 2nd command takes care of both disabling and removing (following the symlinks) the service.
chkconfig was the original command to enable/disable SysVinit services. In systems using systemd , it may be present as a backward compatibility command; but the native systemctl command is just as simple: systemctl disable [servicename]
Okay, but the reason for me using this command is, you then don’t have to explicitly run the rm command
A simple Oneliner could be:
service=YOUR_SERVICE_NAME; systemctl stop $service && systemctl disable $service && rm /etc/systemd/system/$service && systemctl daemon-reload && systemctl reset-failed
Set service to your desired service that should be deleted. E.g. service=gunicorn.service
+1 for a single operation. This could easily be set in a script with the service string as argument, simplifying the process.
Removing a service from systemd :
Systemd uses unit (file to define services) to remove a service the unit have to be removed. here is a list of unit locations :
/etc/systemd/system/ (and sub directories) /usr/local/etc/systemd/system/ (and sub directories) ~/.config/systemd/user/ (and sub directories) /usr/lib/systemd/ (and sub directories) /usr/local/lib/systemd/ (and sub directories) /etc/init.d/ (Converted old service system)
Refresh systemd :
systemctl daemon-reload systemctl reset-failed
Ghost services (not-found) :
Systemd can list ghost (not-found) services even if the unit is deleted for many reasons
- unit still present on one of the systemd directory
- unit does not exit but a file link is still present on one of the systemd directory
- the service is used in other unit(s)*
(*) if a service is mentioned in other unit but does not exist systemd will still list that service with the state not-found even if there is not unit file. you can search what unit is using that service with a text search and edit those units (not recommended if you plan to install that service later)
Sources: Linuxhacks.org
Disclosure: I am the owner of Linuxhacks.org
How to remove a systemd’s service?
To disable a systemd’s service the following command can be used:
systemctl stop service-name; systemctl disable service-name;
Removing a service from systemd:
Systemd uses unit (file to define services) to remove a service the unit file have to be removed, here is a list of unit locations:
/etc/systemd/system/ (and sub directories) /usr/local/etc/systemd/system/ (and sub directories) ~/.config/systemd/user/ (and sub directories) /usr/lib/systemd/ (and sub directories) /usr/local/lib/systemd/ (and sub directories) /etc/init.d/ (Converted old service system)
Refresh/Reload systemd:
systemctl daemon-reload systemctl reset-failed
Ghost services (not-found):
Systemd can list ghost (not-found) services even if the unit is deleted for many reasons
- Unit still present on one of the systemd directory
- Unit does not exit but a file link is still present on one of the systemd directory
- The service is used in other unit(s)*
(*) if a service is mentioned in other unit but does not exist systemd will still list that service with the state not-found even if there is not unit file… you can search what unit is using that service with a text search and edit those units (not recommended if you plan to install that service later)
Posted on 2019-05-29 by intika, viewed times and updated on August 22, 2020.