Service not working: what to check with systemctl before restarting
How to read the systemd service state, distinguish process startup from application readiness, and gather facts before changing the server state.

In this article
Когда сайт недоступен, перезапуск службы кажется самым быстрым действием. Но он может стереть удобный для диагностики контекст и ненадолго скрыть повторяющуюся ошибку. Сначала полезно узнать, запущен ли сервис, чем закончилась последняя попытка и какой именно компонент отвечает за запросы.
Найдите точное имя службы
Инструкция рассчитана на Linux с systemd. В примере используется nginx.service; если у вас другой веб-сервер или контейнерная схема, подставлять это имя без проверки не нужно. Команды просмотра состояния ничего не перезапускают.
systemctl status nginx.service --no-pager --full
В выводе смотрите, загружен ли unit, активен ли он, какой основной процесс связан со службой и какие последние сообщения попали в статус. Если служба не найдена, проверьте её реальное имя и способ запуска приложения. Не устанавливайте новый веб-сервер только для того, чтобы пример команды начал работать.
Получите отдельные свойства
Для компактного результата выполните:
systemctl show nginx.service -p LoadState -p ActiveState -p SubState -p Result -p MainPID
Свойства помогают разделить несколько ситуаций: описание службы отсутствует, процесс остановлен, запуск завершился ошибкой или unit считается активным. Значение active не гарантирует, что сайт отдаёт правильную страницу или успешно обращается к базе данных.
Проверка systemctl is-active nginx.service удобна для сценариев, но её ненулевой код выхода нужно интерпретировать в контексте состояния. Он не заменяет чтение причины отказа. Также не путайте включение автозапуска и текущий запуск: это разные свойства службы.
Сопоставьте службу и пользовательскую ошибку
Предположим, Nginx активен, но запросы заканчиваются ошибкой шлюза. Это совместимо с проблемой приложения за веб-сервером. В таком случае повторный запуск Nginx может не изменить ситуацию: нужно проверить upstream, сокет и журналы связанных служб.
Другой пример — service завершился сразу после старта. Последние строки статуса могут подсказать ошибку конфигурации, но полный журнал за нужное время надёжнее нескольких обрезанных сообщений. Запишите время неудачного запуска и перейдите к ограниченной выборке журнала.
Сохраните данные до вмешательства
Отметьте имя unit, состояние, результат последнего запуска и время инцидента. Если виден идентификатор процесса, проверьте, соответствует ли он ожидаемой программе. Вывод статуса может содержать пути или фрагменты журналов, поэтому перед передачей удалите секреты и данные клиентов.
Не объединяйте диагностику с автоматическим перезапуском в одной скопированной строке. Сначала должно быть понятно, какой сервис затронут и какое действие допускает его рабочая схема. Для одних приложений достаточно исправить зависимость, для других нужен согласованный перезапуск с проверкой текущих операций.
Как подтвердить восстановление
После выбранного администратором действия проверьте состояние службы снова и отдельно выполните обычный пользовательский сценарий. Например, загрузка главной страницы подтверждает только эту страницу; для магазина может понадобиться проверка каталога и оформления тестового заказа. Успешный статус процесса и работоспособность услуги нужно подтверждать отдельно.
When a site is unavailable, restarting the service seems like the fastest action. However, it can erase the context useful for diagnostics and temporarily hide a recurring error. First, it is useful to find out if the service is running, how the last attempt ended, and which specific component handles requests.
Find the exact service name
This guide is designed for Linux with systemd. The example uses nginx.service; if you have a different web server or container setup, do not substitute this name without verification. Status check commands do not restart anything.
systemctl status nginx.service --no-pager --full
In the output, check if the unit is loaded, if it is active, which main process is associated with the service, and what the latest messages in the status are. If the service is not found, check its actual name and the method used to start the application. Do not install a new web server just so that a sample command works.
Get individual properties
To get a compact result, run:
systemctl show nginx.service -p LoadState -p ActiveState -p SubState -p Result -p MainPID
Properties help distinguish several situations: the service description is missing, the process is stopped, the startup failed, or the unit is considered active. A value of active does not guarantee that the site serves the correct page or successfully connects to the database.
Checking systemctl is-active nginx.service is convenient for scenarios, but its non-zero exit code must be interpreted in the context of the status. It does not replace reading the failure reason. Also, do not confuse enabling auto-start with the current running state: these are different service properties.
Match the service and user error
Suppose Nginx is active, but requests end with a gateway error. This is consistent with an application issue behind the web server. In this case, restarting Nginx may not change the situation: you need to check the upstream, the socket, and the logs of related services.
Another example is a service that terminates immediately after starting. The last lines of the status may hint at a configuration error, but a full log for the relevant time is more reliable than several truncated messages. Record the time of the failed start and switch to a limited log selection.
Save data before intervening
Note the unit name, state, result of the last start, and the incident time. If a process ID is visible, check whether it corresponds to the expected program. The status output may contain paths or log fragments, so remove secrets and customer data before passing it on.
Do not combine diagnostics with automatic restart in a single copied line. First, it must be clear which service is affected and what action its operational scheme allows. For some applications, fixing a dependency is sufficient; for others, a coordinated restart with verification of current operations is needed.
How to confirm recovery
After the action selected by the administrator, check the service status again and separately run a standard user scenario. For example, loading the homepage confirms only that page; a store may also require checking the catalog and placing a test order. A successful process status and service operability must be verified separately.

Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.