- Difference between systemctl init.d and service
- 1 Answer 1
- Understanding init.d Directory In Linux Filesystem.
- 📑 Настройка автозапуска скриптов в Linux Ubuntu/Mint
- Создание скрипта в init.d для запуска во время инициализации системы
- Загрузка с помощью rc.local после загрузки системы
- How to use sudo or sudoers to start, stop & restart Apache on Linux Cloud Servers
- CentOS / Fedora
- Ubuntu / Debian
- Related Tutorials
Difference between systemctl init.d and service
I am new to linux and have been testing myself using an Amazon Lightsail instance (Ubuntu 16.04 LTS). Going through the many guides I have came across, I see people using different commands to start/stop/restart/reload/status-check a service. Specifically these;
sudo systemctl status apache2.service sudo /bin/systemctl status apache2.service sudo /etc/init.d/apache2 status sudo service apache2 status
- Should I prefer one command over the other?
- If yes then why?
- Are there any other commands I need to be aware of?
Using init.d in Monit caused issues when I wanted to use the status option (status will be that the service is offline when it was actually online — restarted by Monit). Change the code in Monit from inid.d to /bin/systemctl fixed it.
It seems that using init.d provides more information on what happened that the others. If I should be using one of the other commands, is it possible to have them display more information on what was done?
ubuntu@ip-172-26-12-245:~$ sudo systemctl restart pure-ftpd.service ubuntu@ip-172-26-12-245:~$ sudo /bin/systemctl restart pure-ftpd.service ubuntu@ip-172-26-12-245:~$ sudo /etc/init.d/pure-ftpd restart [ ok ] Restarting pure-ftpd (via systemctl): pure-ftpd.service. ubuntu@ip-172-26-12-245:~$ sudo service pure-ftpd restart ubuntu@ip-172-26-12-245:~$
I would like to thank everyone in advance who has taken the time to read and reply to this question.
In Linux there is often more then one way to perform an action. There is not one that is better or worse or right or wrong. Personally I use the one with the least typing. Many of these commands may be sym links or back compatibility as Ubuntu changes to systemd.
systemctl is the preferred syntax and service is provided as backward compatibility. /etc/init.d/pure-ftpd or similar are calling the start/stop scripts directly.
1 Answer 1
To start, there’s a whole history and struggle between going from SysVInit to SystemD . Rather than trying to break that all down in one answer though, I’ll refer you to some google venturing for more details on the history as well as one particular article on the topic:
In summary though, it’s been a slow and arduous transition. Some legacy features were kept intact (such as init.d to some degree). If you have the option to use systemctl for your service control I recommend using that one. It’s the foreseeable future for Linux and eventually older SysVInit methods will be considered deprecated entirely and removed.
To cover each one you listed specifically:
- sudo systemctl status apache2.service This is the new SystemD approach to handling services. Moving forward, applications on Linux are designed to uses the systemd method, not any other.
- sudo /bin/systemctl status apache2.service This is the same thing as the previous command. The only difference in this case is that it’s not depending on the shell’s $PATH environment variable to find the command, it’s listing the command explicitly by including the path to the command.
- sudo /etc/init.d/apache2 status This is the original SysVInit method of calling on a service. Init scripts would be written for a service and placed into this directory. While this method is still used by many, service was the command that replaced this method of calling on services in SysVInit . There’s some legacy functionality for this on newer systems with SystemD , but newer programs don’t include this, and not all older application init scripts work with it.
- sudo service apache2 status This was the primary tool used on SysVInit systems for services. In some cases it just linked to the /etc/init.d/ scripts, but in other cases it went to an init script stored elsewhere. It was intended to provide a smoother transition into service dependency handling.
Lastly, you mention wanting to know how to get more information out of the commands, since some provide more information than others. This is almost always determined by the application and how they designed their init or service file. As a general rule though, if it completed silently it was successful. However, to verify a start , stop , or restart , you can use the status sub-command to see how it is doing. You mentioned a status command being incorrect on an old init script. That is a bug that the application developers would have to look at. However, since init scripts are becoming the deprecated method of handling services, they may just ignore the bug until they remove the init script option entirely. The systemctl status should always work correctly otherwise a bug should be logged with the application developers.
Understanding init.d Directory In Linux Filesystem.
init.d is the sub-directory of /etc directory in Linux file system. init.d basically contains the bunch of start/stop scripts which are used to control (start,stop,reload,restart) the daemon while the system is running or during boot. If you look at /etc/init.d then you will notice all the scripts for different services of your system.
The scripts within the directory varies as per the applications installed in your system. In server system you’ll find many network related scripts while in desktop there will be the only basic ones like ‘networking’.
There are two types of scripts : K scripts & S scripts.
K scripts are known ‘kill’ scripts while S scripts are known as ‘startup’ scripts. Kill scripts always run before startup scripts. The configuration file (.conf) of these scripts are located under /etc/init & the scripts that are used as defaults are located under /etc/default.
Within /etc/init.d you’ll find the script rc.local ,this script is automatically executed after all primarily priortized scripts are executed. Which means first K scripts are executed, following by S scripts, then all other remaining init level scripts (if there’s any) & finally rc.local script.
Now to control any script, you’ll need the superuser (sudo/su) permission. You can manually control the scripts using console/terminal. The syntax for controlling the script is like :
Where \ stands for the name of the script located under /etc/init.d which you wanna control, and \ can be replaced by the control commands like : start,stop,reload,restart,force-reload.
sudo /etc/init.d/pulseaudio reload
I hope this helps to understand /etc/init.d directory. This was basic understanding of init.d directory, there’s more into it which will be covered soon.
The Geeky Way is founded by Sanyam Khurana. He graduated from Georgia Tech, Atlanta, US with a Master’s degree in Computer Science. He goes by ‘CuriousLearner’ all over the web & has spoken at many international conferences. He likes to contribute to FOSS. He is listed as an individual contributor of the Django project, bug-triager for CPython & has his name listed in the credits section of every browser ever released by Mozilla. In his free time, he likes to improve his guitar skills or binge-watch series.. You can find him on Twitter
Posted on: Sat 07 December 2013
📑 Настройка автозапуска скриптов в Linux Ubuntu/Mint
Здесь рассматриваются способы настройки автозапуска скриптов в Ubuntu/Mint только в консольном режиме.
Создание скрипта в init.d для запуска во время инициализации системы
Для начала нужно создать скрипт и скопировать его в директорию /etc/init.d/ удобным для вас способом, а затем сделать его исполняемым командой:
$sudo chmod +x /etc/init.d/имя_скрипта
Теперь необходимо добавить его в автозагрузку:
$sudo update-rc.d имя_скрипта defaults
Скрипт запуститься во время инициализации системы.
Удалить из автозагрузки можно так:
$sudo update-rc.d -f имя_скрипта remove
Загрузка с помощью rc.local после загрузки системы
Необходимо создать скрипт в любой директории, где вам удобно и сделать его исполняемым как в первом способе.
$sudo chmod +x /etc/init.d/имя_скрипта
Затем подправить файл rc.local любым редактором текста, например nano:
Изначально скрипт rc.local пустой и содержит только:
#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. exit 0
Пропишите полный путь скрипта перед строчкой exit 0 и сохраните файл.
Как сказано в комментариях в эталонном rc.local делаем его исполняемым (хотя во многих дистрибутивах он изначально исполняемый):
Скрипт выполниться после загрузки системы .
Однако в последних версиях Ubuntu (например в Ubuntu 18.04) в директории /etc нет файла rc.local и его необходимо создать и сделать исполняемым:
$ sudo touch /etc/rc.local $ sudo chmod +x /etc/rc.local
Все, скрипт должен автоматически запускаться.
- Настройка автозапуска скриптов в Linux Ubuntu/Mint
- Устанавливаем оболочку bash про умолчанию
- SOCS5 прокси сервер DANTE — установка и настройка
- Работа с сервисами в Ubuntu 16.04
- Установка сервера точного времени NTP в Ubuntu 16.04
- Как протестировать скорость сетевого подключения VDS
- Самоподписанные сертификаты, WP Multisite и cURL
- Создание и подключение swap файла
- Ошибка при обновлении ядра
- Доступ к админке WP по SSL
- Блокирование атак при помощи null route или blackhole
- Добавление нового sudo пользователя
- Блокирование ip адреса при помощи iptables
- fail2ban для защиты WordPress
- Ротация логов — logrotate
- Простая защита в Apache от DOS атак
- Защита сервера — Fail2Ban
- Защита phpMyAdmin
- Русская locale в Ubuntu Server
How to use sudo or sudoers to start, stop & restart Apache on Linux Cloud Servers
sudo permits an allowed user to execute a command as the superuser or another user, as determined in the sudoers document. Setting the original and effective UID and GID to match the target user specified in the passwd file and initializing the group vector based on the group file.
This is a great way to avoid security issues and it requires users to authenticate with passwords by default.
This article will guide you to the basic commands about using sudo or sudoers to start, stop & restart Apache on a common Linux OS.
CentOS / Fedora
- Below are the normal commands to start, stop and restart the Apache with sudo.
# sudo /etc/init.d/httpd start # sudo /etc/init.d/httpd stop # sudo /etc/init.d/httpd restart
**layerstack** is not in the sudoers file. This incident will be reported.
Here layerstack is a standard user that using for giving permission to start/stop/restart Apache Web Server.
Now open /etc/sudoers file with any text editor and add the below line.
layerstack ALL = /etc/init.d/httpd
Ubuntu / Debian
- Below are the commands to start, stop and restart the Apache with sudo.
# sudo /etc/init.d/apache2 start # sudo /etc/init.d/apache2 stop # sudo /etc/init.d/apache2 restart
**layerstack** is not in the sudoers file. This incident will be reported.
Here layerstack is a standard user that using for giving permission to start/stop/restart Apache Web Server.
Now open /etc/sudoers file with any text editor and add the below line.
layerstack ALL = /etc/init.d/apache2