Starting and stopping linux services

Содержание
  1. ИТ База знаний
  2. Полезно
  3. Навигация
  4. Серверные решения
  5. Телефония
  6. Корпоративные сети
  7. Как запустить, остановить и перезапустить сервисы в Linux
  8. Базовый синтаксис команды systemctl
  9. Как проверить, работает ли служба в Linux
  10. Как перезапустить сервис
  11. Как перезагрузить конфигурационные файлы сервиса
  12. Как запустить сервис
  13. Как остановить сервис
  14. Как включить сервис при загрузке
  15. Как отключить сервис при загрузке
  16. Полезно?
  17. Почему?
  18. How to Start, Stop & Restart Services in Ubuntu and Other Linux Distributions
  19. Method 1: Managing services in Linux with systemd
  20. 1. List all services
  21. 2. Start a service
  22. 3. Stop a service
  23. 4. Restart a service
  24. 5. Check the status of a service
  25. Method 2: Managing services in Linux with init
  26. 1. List all services
  27. 2. Start a service
  28. 3. Stop a service
  29. 4. Restart a service
  30. 5. Check the status of a service
  31. How to Start, Stop, and Restart Services in Linux
  32. Basic Syntax of systemctl Command
  33. How To Check If a Service is Running on Linux
  34. How to Restart a Service
  35. How to Reload a Service
  36. How to Start a Service
  37. How to Stop a Service
  38. How to Enable the Service at Boot
  39. How to Disable Service at Boot
  40. Variations in Service Names
  41. How to list, start and stop services at boot time in Linux Ubuntu/Debian
  42. List startup services at boot time
  43. 1 – systemctl
  44. Services that started before a given service
  45. Services that started after a given service
  46. 2 service command
  47. 3 – Checking a specific service enability status
  48. 4 – Checking a specific service status
  49. Enabling a specific service at boot time
  50. Disabling a specific service at boot time
  51. Stopping a specific service
  52. Starting and Restarting a specific service
  53. Displaying services error messages/logs
  54. Starting a Conflicting Service
  55. Comparison of systemctl with the service tool

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Как запустить, остановить и перезапустить сервисы в Linux

Start — Stop — Restart — Reload

3 минуты чтения

Linux обеспечивает детальный контроль над системными службами через systemd с помощью команды systemctl. Службы могут быть включены, выключены, перезапущены, перезагружены или даже включены или отключены при загрузке. Если вы используете Debian, CentOSили Ubuntu, ваша система, вероятно, использует systemd.

Мини — курс по виртуализации

Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

Это руководство покажет вам, как использовать основные команды для запуска, остановки и перезапуска служб в Linux.

Базовый синтаксис команды systemctl

Основной синтаксис для использования команды systemctl:

Как правило, вам нужно запускать это как суперпользователь поэтому команды будут начинаться с sudo.

Как проверить, работает ли служба в Linux

Чтобы проверить, активна ли служба или нет, выполните следующую команду:

Замените SERVICE_NAME на нужный сервис.

В нашем случае мы будем брать за пример веб-сервер Apache.

Интересный факт: в Ubuntu и других дистрибутивах на основе Debian служба Apache называется apache2. В CentOS и других дистрибутивах RedHat служба Apache называется httpd или httpd.service

Так мы проверили состояние Apache. Выходные данные показывают, что служба активна (работает), как на рисунке ниже:

Как перезапустить сервис

Чтобы остановить и перезапустить службу в Linux, используйте команду:

Где SERVICE_NAME — имя вашего сервиса.

После выполнения команды ваш сервис должен снова заработать. Вы можете проверить состояние с помощью команды status

Для перезапуска нашего сервера Apache используем:

Как перезагрузить конфигурационные файлы сервиса

Чтобы служба перезагрузила свои файлы конфигурации, введите в терминале следующую команду:

После перезагрузки проверьте ее состояние командой status для подтверждения.

В нашем примере мы перезагрузили Apache, используя:

Как запустить сервис

Чтобы запустить службу в Linux вручную, введите в терминале следующее:

Например, команда для запуска службы Apache:

Как остановить сервис

Чтобы остановить активную службу в Linux, используйте следующую команду:

Для нашего апача используем команду

Проверьте, остановился ли сервис с помощью команды status . Вывод должен показать, что сервис неактивен — inactive (dead)

Как включить сервис при загрузке

Чтобы настроить службу для запуска при загрузке системы, используйте команду:

Чтобы включить Apache при загрузке системы, выполните команду:

Как отключить сервис при загрузке

Вы можете запретить запуск службы при загрузке с помощью команды:

Мини — курс по виртуализации

Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

Полезно?

Почему?

😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.

😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.

Читайте также:  Windows update checking if your computer

Источник

How to Start, Stop & Restart Services in Ubuntu and Other Linux Distributions

Last updated October 29, 2020 By Sergiu 9 Comments

Services are essential background processes that are usually run while booting up and shut down with the OS.

If you are a sysadmin, you’ll deal with the service regularly.

If you are a normal desktop user, you may come across the need to restart a service like setting up Barrier for sharing mouse and keyboard between computers. or when you are using ufw to setup firewall.

Today I will show you two different ways you can manage services. You’ll learn to start, stop and restart services in Ubuntu or any other Linux distribution.

systemd vs init

Ubuntu and many other distributions these days use systemd instead of the good old init.

In systemd, you manage sevices with systemctl command.

In init, you manage service with service command.

You’ll notice that even though your Linux system uses systemd, it is still able to use the service command (intended to be used with init system). This is because service command is actually redirect to systemctl. It’s sort of backward compatibility introduced by systemd because sysadmins were habitual of using the service command.

I’ll show both systemctl and service command in this tutorial.

I am Ubuntu 18.04 here, but the process (no pun intended) is the same for other versions.

Method 1: Managing services in Linux with systemd

I am starting with systemd because of the obvious reason of its widespread adoption.

1. List all services

In order to manage the services, you first need to know what services are available on your system.

You can use the systemd command to list all the services on your Linux system:

This command will output the state of all services. The value of a service’s state can be enabled, disabled, masked (inactive until mask is unset), static and generated.

Combine it with the grep command and you can display just the running services:

Now that you know how to reference all different services, you can start actively managing them.

Note: in the commands should be replaced by the name of the service you wish to manage (e.g. network-manager, ufw etc.).

2. Start a service

To start a service in Linux, you just need to use its name like this:

3. Stop a service

To stop a systemd service, you can use the stop option of systemctl command:

4. Restart a service

To restart a service in Linux with systemd, you can use:

5. Check the status of a service

You can confirm that you have successfully executed a certain action by printing the service status:

This will output information in the following manner:

That was systemd. Let’s switch to init now.

Method 2: Managing services in Linux with init

The commands in init are also as simple as system.

1. List all services

To list all the Linux services, use

The services preceded by [ – ] are disabled and those with [ + ] are enabled.

2. Start a service

To start a service in Ubuntu and other distributions, use this command:

3. Stop a service

Stopping a service is equally easy.

4. Restart a service

If you want to restart a service, the command is:

5. Check the status of a service

Furthermore, to check if your intended result was achieved, you can output the service status:

This will output information in the following manner:

This will, most importantly, tell you if a certain service is active (running) or not.

Wrapping Up

Today I detailed two very simple methods of managing services on Ubuntu or any other Linux system. I hope this article was helpful to you.

Which method do you prefer? Let us know in the comment section below!

Like what you read? Please share it with others.

Источник

How to Start, Stop, and Restart Services in Linux

Home » SysAdmin » 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
Читайте также:  Blink sip client windows

Basic Syntax of systemctl Command

The basic syntax for using the systemctl command is:

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:

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:

After this point, your service should be up and running again. You can verify the state with the status command.

How to Reload a Service

To force the service to reload its configuration files, type in the following command in the terminal:

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:

How to Start a Service

To start a service in Linux manually, type in the following in the terminal:

For instance, the command to start the Apache service is:

How to Stop a Service

To stop an active service in Linux, use the following command:

If the service you want to stop is Apache, the command is:

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:

To enable Apache upon booting the system, run the command:

How to Disable Service at Boot

You can prevent the service from starting at boot with the command:

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.

Источник

How to list, start and stop services at boot time in Linux Ubuntu/Debian

Services which are also known as daemons, are scripts and programs that run in the background. These services, which require no user input, can provide many functionalities like database services (such as MySQL), or web server services (like Tomcat) etc…

Over time however, the number of services can increase substantially and users might overlook which applications are currently running.

Knowing the services that start at boot time is therefore useful for instance if you have noticed that your system has been running slow. Some unnecessary background services might consume additional RAM and SWAP memories as well as CPU power which leaves less room for important programs. Killing these ‘junk’ services or preventing them from starting at boot might ‘relieve’ your system and improve its performance.

In this short tutorial, you will learn how to display all Ubuntu startup services at boot time in and how to start and stop them.

List startup services at boot time

There are many options that allow us to see the list of services at boot time. We will outline below the most commonly used tools .

1 – systemctl

systemctl is the central management utility that controls the systemd system, manages the services and examine the system state.
In order to list out all services along with their corresponding statuses using systemct , open up your terminal and type in the command below :

systemctl -at service

systemctl list services

Now to single out only those services that are active, go ahead and run the command below :

systemctl -t service –state=active

Linux list services

For the services that are enabled however, you would need to invoke the command below :

systemctl list-unit-files –state=enabled

As an alternative to the command above, it is also possible to use grep command as follows :

Читайте также:  Windows server 2016 rtm build

systemctl list-unit-files | grep enabled

In order to display the list of all currently loaded service units, type in the command below :

systemctl list-units –type service

This command displays, for each service unit file, its full name (UNIT) , its loaded status (LOAD), its high-level (ACTIVE) unit file activation state followed by low-level (SUB) unit file activation state and finally a short description (DESCRIPTION).

The command ‘systemctl list-units’ displays, by default, only active units. In order to display a list of all loaded units (all states), you could execute this command with the –all or -a command line switches as follows:

systemctl list-units –type service –all

Services that started before a given service

In order to find out the services which ordered to start before a specified service, type in the following command in the terminal:

systemctl list-dependencies –after ssh.service

Linux start service

Where you are able to see the services ordered to start before the service named ssh in the snapshot above.

Services that started after a given service

To determine the services which ordered to after after a specified service (ssh here), run the following command:

systemctl list-dependencies before ssh.service

2 service command

The ‘service’ command utility allows to start, restart and stop and daemons as well as other services in Linux. In order to display the list of all services , run the command below :

Ubuntu list services

3 – Checking a specific service enability status

In order to check whether a specific service was enabled at boot time, you could run the following syntax:

systemctl is-enabled service_name.service

here the service name is ssh.

4 – Checking a specific service status

In order to see the status of a given service (enability flag is also provided as highlighted below), the following commands could be executed :

systemctl status service_name.service

As an alternative to the command above, you could also use the command below :

systemctl list-unit-files –type service

The following table shows the service units information :

You may be interested to read: Network configuration in Ubuntu

Enabling a specific service at boot time

It is possible to enable a single service by using the one of the commands below :

sudo systemctl enable

sudo systemctl enable service_name.service

Disabling a specific service at boot time

Much like enabling a service, systemctl is also able to disable a service by using one of the commands below :

sudo systemctl disable

sudo systemctl disable service_name.service

Disabling a service prevents it (its service unit) from being automatically started at boot time.

This will read the [Install] section of the specific service unit and deletes the appropriate symbolic links to the file /usr/lib/systemd/system/name.service from the directory /etc/systemd/system/ and its subdirectories. Furthermore, you would be able to mask any service unit in order to prevent it from being started by another service or manually. To carry this out, execute the following command as root:

systemctl mask name.service

Stopping a specific service

Stopping a specific active service can be achieved via one the commands below (linux stop service) :

sudo systemctl stop

sudo systemctl stop service_name.service

Starting and Restarting a specific service

Starting a specific inactive service can be done via one the commands below :

sudo systemctl start

sudo systemctl start service_name.service

For the restart :

sudo systemctl restart

sudo systemctl restart service_name.service

Displaying services error messages/logs

To check error messages or logs related to the services, execute one of the commands below :

or as an alternative :

journalctl -u service_name.service

Starting a Conflicting Service

Both negative and positive dependencies between services exist in systemd . Starting a specific service may be dependent on one or more other services (.i.e. positive dependency). Negative dependency is similar but the dependency is related to stopping one or more services.

When you try to start a new service, all dependencies are resolved automatically by systemd . The user does not get notified (explicitly) in this case . In case a service is already running, and at the same time you try to start yet another service which has a negative dependency, the first service in this case, will be automatically stopped.

For instance, if the postfix service is already running and you attempt to start the sendmail service, systemd will first automatically stop the first service, i.e. postfix, since these two services are conflicting as they cannot be executed on the same port.

Comparison of systemctl with the service tool

If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

Источник

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