How to restart nginx
How to restart nginx
Как запустить, остановить или перезапустить Nginx
How to Start, Stop, or Restart Nginx
В этом руководстве мы объясним, как запускать, останавливать и перезапускать Nginx на серверах Linux.
Если вы разработчик или системный администратор, скорее всего, вы регулярно работаете с Nginx. Запуск, остановка и перезапуск / перезагрузка являются наиболее распространенными задачами при работе с веб-сервером Nginx.
Прежде чем вы начнете
Большинство современных дистрибутивов Linux используют SystemD в качестве системы инициализации по умолчанию и менеджера сервисов. Старые дистрибутивы основаны на SysVinit и используют сценарии инициализации для управления сервисами.
И служебные модули SystemD, и сценарий SysVinit принимают следующие аргументы для управления службой Nginx:
Команды для управления службой Nginx одинаковы во всех дистрибутивах Linux.
Запустите, остановите и перезапустите Nginx, используя systemctl
Всякий раз, когда вы вносите изменения в конфигурацию Nginx, вам необходимо перезапустить или перезагрузить процессы веб-сервера. Выполните следующую команду, чтобы перезапустить службу Nginx:
При добавлении или редактировании серверных блоков предпочитайте перезагрузку, а не перезапуск. Перезапускайте службу только при внесении значительных изменений, таких как изменение портов или интерфейсов. При перезагрузке Nginx загружает новую конфигурацию, запускает новые рабочие процессы с новой конфигурацией и корректно завершает работу старых рабочих процессов.
Выполните команду ниже, чтобы перезагрузить службу Nginx:
Nginx также может напрямую контролироваться с помощью команд. Например, чтобы перезагрузить сервис, вы можете использовать следующую команду:
Чтобы запустить службу Nginx, выполните следующую команду:
Выполните следующую команду, чтобы остановить службу Nginx:
Запустите, остановите и перезапустите Nginx, используя SysVinit
Старые (EOLed) версии Ubuntu, CentOS и Debian используют сценарии init.d для запуска, остановки и перезапуска демона Nginx.
Перезапустите сервис Nginx:
Запустите сервис Nginx:
Остановите службу Nginx:
Вывод
В этом руководстве мы показали, как запускать, останавливать и перезапускать веб-сервер Nginx в системах Linux.
Как перезапустить Nginx
Если вы начинающий администратор или только перенесли свой проект на VPS и еще не со всем разобрались, то у вас может возникнуть вопрос как перезапустить Nginx. Это очень популярный веб-сервер, такой же популярный, как и Apache и достаточно часто используется для различных проектов.
Перезапуск веб-сервера может понадобиться после того, как вы изменили его настройки, добавили новый домен и так далее. В этой небольшой статье мы рассмотрим как выполняется перезагрузка Nginx на сервере.
Как перезапустить Nginx
Первое что желательно сделать если вы меняли настройки Nginx, и что-то делали с конфигурационными файлами, это проверить их на ошибки с помощью команды:
Если это производственный сервер, то пользователи вообще не должны заметить что был перезапуск Nginx, а если будут проблемы то после установки веб-сервер не запустится и будет лежать пока вы их не решите. Только теперь можно перезапустить Nginx:
systemctl restart nginx
Если нужно только перечитать конфигурационные файлы выполните:
systemctl reload nginx
В случае если обычная перезагрузка не помогла, можно попытаться остановить сервис, а затем снова его запустить:
systemctl status nginx
systemctl stop nginx
systemctl start nginx
Перезапуск Nginx с помощью ISPManager
Панель управления VPS ISPManager довольно популярна среди пользователей и если вы используете ее на своем сервере, то можете перезапустить Nginx с помощью нее. Для этого авторизуйтесь в панели, перейдите на вкладку «Система», «Службы», а затем найдите там пункт «Nginx», выделите его и нажмите кнопку «Перезапуск»:
Готово, теперь Nginx перезапущен.
Выводы
В этой небольшой статье мы рассмотрели как перезапустить Nginx на вашем сервере. Если у вас остались вопросы, спрашивайте в комментариях!
Конференция HighLoad в которой рассказывается что нового в Nginx:
How To Restart Nginx Web Server?
Nginx is a popular web server that is an alternative to the other web servers like Apache, IIS, etc. Nginx is a free open-source, high-performance initiative web and reverses proxy server. Nginx provides better performance against Apache and IIS. Most of the Linux system administrators deal with the Nginx web server in daily operations. In this tutorial, we will examine and learn how to restart (stop&start) Nginx server using different methods and commands like systemctl, service, nginx command, kill command, etc.
Why Restart Nginx?
Before restart the Nginx server or service you should have a valid reason to restart it. Especially in a critical application, the Nginx server may not start properly which will interrupt the service and create stress for you. The following reasons can be listed to restart the Nginx server.
Restart Forcibly or Gracefully?
In general Nginx web server can be restarted in 2 different ways. They are called Forcibly Restart or Gracefully Restart. Forcibly Restart will restart the main Nginx and child processes immediately where the user session will be lost. Gracefully restart will first start a new child process with the new configuration and then stop and start the main process.
Show Nginx Service Status and Last Start Time
Before restart the Nginx listing and showing the current start of the Nginx service and server will be very useful. Also, the last start time can be listed with the systemctl status command like below. The Nginx service name is nginx or nginx.service
Restart With systemctl Command
The easiest, straightforward, and reliable way to restart the Nginx server or service is using the systemctl restart command. The systemctl command provided by most of the Linux distributions like Ubuntu, Debian, Mint, CentOS, RHEL, SUSE, etc.
If the Nginx service is restarted properly without a problem we will see nothing on the command-line. If there is an error like configuration, permission, etc. the error will be printed to the terminal/command line. In the following example, there is a permission error and the Nginx service couldn’t be started successfully.
Restart Gracefully With systemctl Command
We can also restart the Nginx gracefully by using the systemctl reload command. As stated previously graceful restart will create new child or worker processes with the new configuration and then stop old Nginx processes properly.
Or with the full Nginx service name
Restart With /etc/init.d/nginx SystemV Script
SystemV is an old service management way for Linux, Unix, and BSD systems. Even replaced with the systemd/systemctl SystemV init.d scripts can be used to restart the Nginx service.
Restart Gracefully /etc/init.d/nginx SystemV Script
SystemV init.d script also provides a graceful restart method with the nginx reload script like below.
Restart with nginx Command
Restart With service Command
service command is another alternative to restart Nginx webserver service. service restart will be used to restart the Nginx server which is named nginx like below.
Restart Gracefully With service Command
the service command also provides the grafecul restart ability with the service reload command like below.
Restart Nginx In Windows
Restart Nginx At Specific Periods with cron
Sometimes you may have problems with the server software or web application that runs on the Nginx web server. This problematic web application can block or crash the Nginx server. In this case, restarting the Nginx server periodically may help reduce the problem even it is not a perfect solution. You can use cron to restart Nginx service like below.
Test and Check Nginx Server Configuration and Errors
How to Start, Stop, and Restart Nginx (systemctl & Nginx Commands)
Home » SysAdmin » How to Start, Stop, and Restart Nginx (systemctl & Nginx Commands)
Nginx is a powerful server application that routes network traffic. It’s often used as a reverse proxy server, but can also be configured as a regular web server.
One of the most common operations you will encounter is starting, stopping, and restarting the Nginx web server.
In this tutorial, learn how to start, stop, and restart the Nginx service.
Note: If you haven’t installed Nginx yet, refer to our guides on Installing Nginx on Ubuntu or Installing Nginx on CentOS 8.
Start, Stop, and Restart Nginx with systemctl
How to View Status of Your Nginx Server
Nginx runs as a service on your server. That means that it should be actively running in the background, even if you don’t see anything on the screen. You can display the status of the Nginx service by entering the following command in a terminal window:
The system will switch into a status mode, displaying lots of information about the Nginx service.
Press q to reactivate the bash prompt.
SystemD is the default service manager on modern versions of Linux distributions (Ubuntu 20.04/18.04/16.04, CentOS 7/7, and Debian 9/10). The SystemD manager functions through the systemctl command.
The systemctl command is a base Linux command. That means that it can be used for any Linux service.
Stop and Start Nginx
systemctl can be used to start and stop the Nginx service.
To stop Nginx, run the following command:
To start Nginx, execute the systemctl command with the start option:
How to Restart Nginx
Gracefully Restart Nginx
If you’re refreshing Nginx after changing the configuration, it’s best to gracefully reload the service. That shuts down old processes and restarts new ones with the new configuration.
Use the systemctl Linux command to reload the Nginx service. Run the following command:
Note: Nginx cannot be reloaded if the the Nginx service is not active.
Force Restart Nginx
For major configuration changes, you can force a full restart of Nginx. This force-closes the whole service and sub-processes, and restarts the whole package.
Enter the following command:
Restart vs Reload Nginx
The reload command keeps the Nginx server running as it reloads updated configuration files. If Nginx notices a syntax error in any of the configuration files, the reload is aborted and the server keeps running based on old config files. Reloading is safer than restarting Nginx.
The restart command will shut down the server including all related services and power it on again. Restart Nginx only when making significant configuration updates, such as changing ports or interfaces. This command will force shut down all worker processes.
Configure Nginx to Launch on Boot
Use the enable option with the systemctl command to enable Nginx:
Use the disable option with the systemctl command to disable Nginx:
Start, Stop, and Reload Nginx with the Nginx Command
Nginx has a set of built-in tools for managing the service that can be accessed using the Nginx command.
Nginx Start
To start Nginx and related processes, enter the following:
If run successfully, the terminal output will display the following:
Nginx Restart
To force close and restart Nginx and related processes:
Nginx Stop
To disable or stop the Nginx service, enter the following:
Nginx Reload
To gracefully stop and restart Nginx and related processes, use the command:
Nginx Quit
This article has outlined several methods to start, stop, and restart Nginx on your server. Use these commands for the most common operations when managing an Nginx web server.
Start, Stop, and Restart Nginx Web Server on Linux
Igor Sysoev created it to overcome the limits of scaling and concurrency existing within regular web servers, offering an event-based, asynchronous architecture that enhances NGINX’s performance and stability as a web server.
As is the case with managing all servers, you’ll find yourself needing to start, stop, and restart the NGINX web server for various reasons.
This guide discusses how to use various methods to manage the NGINX service running on a Linux system.
NOTE: If you are running NGINX on a remote server, you will need to have an SSH connection. Ensure you also have sudo or root access to your system.
How to Manage the NGINX Service With The Systemd Service Manager
One way to manage NGINX service is by using the systemd service manager, commonly accessible using the systemctl command. This method will only work if the system where NGINX is installed uses systemd as its service manager.
How to View the NGINX web server status
In most cases, NGINX is installed as a service and runs in the background. Although NGINX runs in the background, there are ways to view the service status using the systemctl utility.
To view how the service is running, open the terminal window, and enter the command:
The command above will display information about the NGINX service. The command will display either of the following scenarios.
NOTE: Press Q to quit from status mode to shell.
How To Use systemd to Start and Stop the Nginx Service
Systemd is a universal utility that manages services in most Linux distribution. If NGINX is configured to run as a service, we can use the systemd to start and stop it.
To start the Nginx service, use the command:
To stop Nginx, use the command:
How to Use systemd to restart the NGINX Service
You can also use the systemd to restart the NGINX service. Restarting a service shuts down all the running processes and restarts them afresh. Restarting a service is very useful when applying configuration changes to the server, eliminating the need to reboot the entire system.
There are two ways to restart a service:
How to Reload the Nginx Service (Graceful restart)
To restart the NGINX service gracefully using systemd, use the command:
The above command requires the service to be running.
How to Force Restart Nginx Service
If you are performing critical changes to the NGINX server, you should reboot the service. Restarting force-closes all running processes, reinitializes them, and applies new changes. This is very useful when performing updates, changing ports, network interfaces, etc.
You can use the command:
How to Manage The NGINX Service With Nginx Commands
NGINX has a set of built-in tools that are accessible using the Nginx command. We can use these commands to interact with the service manually.
How to use Nginx commands to start NGINX
You can start the NGINX service using the command
This command will display the output indicating that the service is starting—as shown in the image below:
How to stop the NGINX web server using Nginx commands
To stop the Nginx service and all related processes, you can use the command:
You will get an output such as the one shown below:
How to force-close and restart the NGINX web server using a command
You can also force close and restart all nginx processes using the command:
How to reload the NGINX web server using a command
To reboot the nginx service and its processes gracefully, you use the command:
How to force-terminate the NGINX server a using command
If you want to force-close all Nginx services without rebooting, use the command
Conclusion
In this article, we have discussed various methods you can use to interact with the NGINX service. Using what you’ve learned, you can manage the Nginx web server and troubleshoot server related problems.
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list