- Как запустить, остановить и перезапустить сервисы в Linux
- Базовый синтаксис команды systemctl
- Как проверить, работает ли служба в Linux
- Как перезапустить сервис
- Как перезагрузить конфигурационные файлы сервиса
- Как запустить сервис
- Как остановить сервис
- Как включить сервис при загрузке
- Как отключить сервис при загрузке
- How to use systemctl to manage Linux services
- Restart a service
- Stop and start a service
- Training & certification
- Control whether the service starts with the system
- Mask a service
- Display all subcommands
- The challenge
- Automation advice
- Wrap up
- How to Start, Stop, and Restart Services in Linux
- Basic Syntax of systemctl Command
- How To Check If a Service is Running on Linux
- How to Restart a Service
- How to Reload a Service
- How to Start a Service
- How to Stop a Service
- How to Enable the Service at Boot
- How to Disable Service at Boot
- Variations in Service Names
Как запустить, остановить и перезапустить сервисы в Linux
Linux обеспечивает детальный контроль над системными службами через systemd с помощью команды systemctl. Службы могут быть включены, выключены, перезапущены, перезагружены или даже включены или отключены при загрузке. Если вы используете Debian, CentOSили Ubuntu, ваша система, вероятно, использует systemd.
Это руководство покажет вам, как использовать основные команды для запуска, остановки и перезапуска служб в Linux.
Базовый синтаксис команды systemctl
Основной синтаксис для использования команды systemctl:
systemctl [command] [service_name]
Как правило, вам нужно запускать это как суперпользователь поэтому команды будут начинаться с sudo.
Как проверить, работает ли служба в Linux
Чтобы проверить, активна ли служба или нет, выполните следующую команду:
sudo systemctl status SERVICE_NAME
Замените SERVICE_NAME на нужный сервис.
В нашем случае мы будем брать за пример веб-сервер Apache.
Интересный факт: в Ubuntu и других дистрибутивах на основе Debian служба Apache называется apache2. В CentOS и других дистрибутивах RedHat служба Apache называется httpd или httpd.service
sudo systemctl status apache2
Так мы проверили состояние Apache. Выходные данные показывают, что служба активна (работает), как на рисунке ниже:
Как перезапустить сервис
Чтобы остановить и перезапустить службу в Linux, используйте команду:
sudo systemctl restart SERVICE_NAME
Где SERVICE_NAME — имя вашего сервиса.
После выполнения команды ваш сервис должен снова заработать. Вы можете проверить состояние с помощью команды status
Для перезапуска нашего сервера Apache используем:
sudo systemctl restart apache2
Как перезагрузить конфигурационные файлы сервиса
Чтобы служба перезагрузила свои файлы конфигурации, введите в терминале следующую команду:
sudo systemctl reload SERVICE_NAME
После перезагрузки проверьте ее состояние командой status для подтверждения.
В нашем примере мы перезагрузили Apache, используя:
sudo systemctl reload apache2
Как запустить сервис
Чтобы запустить службу в Linux вручную, введите в терминале следующее:
sudo systemctl start SERVICE_NAME
Например, команда для запуска службы Apache:
sudo systemctl start apache2
Как остановить сервис
Чтобы остановить активную службу в Linux, используйте следующую команду:
sudo systemctl stop SERVICE_NAME
Для нашего апача используем команду
sudo systemctl stop apache2
Проверьте, остановился ли сервис с помощью команды status . Вывод должен показать, что сервис неактивен — inactive (dead)
Как включить сервис при загрузке
Чтобы настроить службу для запуска при загрузке системы, используйте команду:
sudo systemctl enable SERVICE_NAME
Чтобы включить Apache при загрузке системы, выполните команду:
sudo systemctl enable apache2
Как отключить сервис при загрузке
Вы можете запретить запуск службы при загрузке с помощью команды:
sudo systemctl disable SERVICE_NAME
sudo systemctl disable apache2
How to use systemctl to manage Linux services
Suppose you’re making configuration changes to a Linux server. Perhaps you just fired up Vim and made edits to the /etc/ssh/sshd_config file, and it’s time to test your new settings. Now what?
Services such as SSH pull their settings from configuration files during the startup process. To let the service know about changes to the file, you need to restart the service so that it rereads the file. You can use the systemctl command to manage services and control when they start.
Restart a service
After editing the /etc/ssh/sshd_config file, use the systemctl restart command to make the service pick up the new settings:
$ sudo systemctl restart sshd
You can verify the service is running by using the status subcommand:
$ sudo systemctl status sshd
Stop and start a service
Perhaps while troubleshooting you need to stop a service to determine whether it is the culprit or interfering with some other process. Use the stop subcommand for this:
Once you determine if this service is associated with the issue, you can restart it:
$ sudo systemctl start sshd
Training & certification
While the restart subcommand is useful for refreshing a service’s configuration, the stop and start features give you more granular control.
Control whether the service starts with the system
One consideration with using stop and start is that the two commands apply only to the current runtime. The next time you boot the system, the service will either start or not start, depending on its default settings. You can use the enable and disable subcommands to manage those defaults.
When you disable the service, it doesn’t start the next time the system boots. You might use this setting as part of your security hardening process or for troubleshooting:
$ sudo systemctl disable sshd
Reboot the system with reboot sudo systemctl reboot , and the service won’t automatically start.
You may determine that you need the service to start automatically. In that case, use the enable subcommand:
$ sudo systemctl enable sshd
The enable subcommand doesn’t start a service, it only marks it to start automatically at boot. To enable and start a service at the same time, use the —now option:
$ sudo systemctl enable --now sshd
Mask a service
You can manually start a disabled service with the systemctl start command after the system boots. To prevent this, use the mask subcommand. Masking the service links its configuration to /dev/null . A user or process will not be able to start this service at all (whereas with a disabled service, a user or process can still start it). Use the unmask subcommand to reverse the setting:
Display all subcommands
Bash’s built-in tab-completion feature is one of my favorite tricks for systemctl (and other commands). When working with commands that support subcommands, this feature saves you a lot of time. Simply type systemctl and add a space, then tap the Tab key twice. Bash displays all available subcommands.
The challenge
Do you think you’re ready to use systemctl to manage your services? Fire up a lab virtual machine and choose a service to work with. Don’t do this on a production system! Make sure you can accomplish the following tasks:
Automation advice
Wrap up
Many management tasks involve the systemctl command, but the ones covered above represent the majority of them. Service management is critical, especially when editing configuration files and hardening a system. Plan to be confident, competent, and quick at using systemctl and its common subcommands.
How to Start, Stop, and Restart Services in Linux
Linux provides fine-grained control over system services through systemd, using the systemctl command. Services can be turned on, turned off, restarted, reloaded, or even enabled or disabled at boot. If you are running Debian 7, CentOS 7, or Ubuntu 15.04 (or later), your system likely uses systemd.
This guide will show you how to use basic commands to start, stop, and restart services in Linux.
- Access to a user account with sudo or root privileges
- Access to a terminal/command line
- The systemctl tool, included in Linux
Basic Syntax of systemctl Command
The basic syntax for using the systemctl command is:
systemctl [command] [service_name]
Typically, you’ll need to run this as a superuser with each command starting with sudo .
How To Check If a Service is Running on Linux
To verify whether a service is active or not, run this command:
sudo systemctl status apache2
Replace apache2 with the desired service. In our case, we checked the status of Apache. The output shows that the service is active (running), as in the image below:
How to Restart a Service
To stop and restart the service in Linux, use the command:
sudo systemctl restart SERVICE_NAME
After this point, your service should be up and running again. You can verify the state with the status command.
sudo systemctl restart apache2
How to Reload a Service
To force the service to reload its configuration files, type in the following command in the terminal:
sudo systemctl reload SERVICE_NAME
After reloading, the service is going to be up and running. Check its state with the status command to confirm.
In our example, we reloaded Apache using:
sudo systemctl reload apache2
How to Start a Service
To start a service in Linux manually, type in the following in the terminal:
sudo systemctl start SERVICE_NAME
For instance, the command to start the Apache service is:
sudo systemctl start apache2
How to Stop a Service
To stop an active service in Linux, use the following command:
sudo systemctl stop SERVICE_NAME
If the service you want to stop is Apache, the command is:
sudo systemctl stop apache2
Check whether the service stopped running with the status command. The output should show the service is inactive (dead).
How to Enable the Service at Boot
To configure a service to start when the system boots, use the command:
sudo systemctl enable SERVICE_NAME
To enable Apache upon booting the system, run the command:
sudo systemctl enable apache2
How to Disable Service at Boot
You can prevent the service from starting at boot with the command:
sudo systemctl disable SERVICE_NAME
sudo systemctl disable apache2
Variations in Service Names
If you work within the same Linux environment, you will learn the names of the services you commonly use.
For example, if you are building a website, you will most likely use systemctl restart apache2 frequently, as you refresh configuration changes to your server.
However, when you move between different Linux variants, it is helpful to know that the same service may have different names in different distributions.
For example, in Ubuntu and other Debian based distributions, the Apache service is named apache2. In CentOS 7 and other RedHat distros, the Apache service is called httpd or httpd.service.
In most modern Linux operating systems, managing a service is quite simple using the commands presented here.
Make sure to know the name of the service for the operating system you are using, and the commands in this article should always work.