- 10 Most Used Nginx Commands Every Linux User Must Know
- Install Nginx Server
- Check Nginx Version
- Check Nginx Configuration Syntax
- Start Nginx Service
- Enable Nginx Service
- Restart Nginx Service
- View Nginx Service Status
- Reload Nginx Service
- Stop Nginx Service
- Show Nginx Command Help
- Проверка конфигурации и перезапуск Nginx
- Как протестировать конфигурацию и перезапустить nginx
10 Most Used Nginx Commands Every Linux User Must Know
Nginx (pronounced Engine x) is a free, open-source, high-performance, scalable, reliable, full-featured and popular HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server.
Nginx is well known for its simple configuration, and low resource consumption due to its high performance, it is being used to power several high-traffic sites on the web, such as GitHub, SoundCloud, Dropbox, Netflix, WordPress and many others.
In this guide, we will explain some of the most commonly used Nginx service management commands that, as a developer or system administrator, you should keep at your fingertips. We will show commands for both Systemd and SysVinit.
All of these following list of Nginx popular commands must be executed as a root or sudo user and should work on any modern Linux distribution such as CentOS, RHEL, Debian, Ubuntu and Fedora.
Install Nginx Server
To install Nginx web server, use your default distribution package manager as shown.
$ sudo yum install epel-release && yum install nginx [On CentOS/RHEL] $ sudo dnf install nginx [On Fedora] $ sudo apt install nginx [On Debian/Ubuntu]
Check Nginx Version
To check the version of Nginx web server installed on your Linux system, run the following command.
$ nginx -v nginx version: nginx/1.12.2
The above command simply displays the version number. If you want to view version and configure options then use the -V flag as shown.
nginx version: nginx/1.12.2 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) built with OpenSSL 1.0.2k-fips 26 Jan 2017 TLS SNI support enabled configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_auth_request_module --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'
Check Nginx Configuration Syntax
Before you actually start the Nginx service, you can check whether its configuration syntax is correct. This is especially useful if you have made changes or added a new configuration to the existing configuration structure.
To test the Nginx configuration, run the following command.
$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
You can test the Nginx configuration, dump it and exit using the -T flag as shown.
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful # configuration file /etc/nginx/nginx.conf: # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events < worker_connections 1024; >http < log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server < listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / < >error_page 404 /404.html; location = /40x.html < >error_page 500 502 503 504 /50x.html; location = /50x.html < >> .
Start Nginx Service
To start the Nginx service, run the following command. Note that this process may fail if the configuration syntax is not OK.
$ sudo systemctl start nginx #systemd OR $ sudo service nginx start #sysvinit
Enable Nginx Service
The previous command only starts the service for the meantime, to enable it auto-start at boot time, run the following command.
$ sudo systemctl enable nginx #systemd OR $ sudo service nginx enable #sysv init
Restart Nginx Service
To restart the Nginx service, an action which will stop and then start the service.
$ sudo systemctl restart nginx #systemd OR $ sudo service nginx restart #sysv init
View Nginx Service Status
You can check the Nginx service’s status as follows. This command shows the run time status information about the service.
$ sudo systemctl status nginx #systemd OR $ sudo service nginx status #sysvinit
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service. [[email protected] ~]# systemctl status nginx ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2019-03-05 05:27:15 EST; 2min 59s ago Main PID: 31515 (nginx) CGroup: /system.slice/nginx.service ├─31515 nginx: master process /usr/sbin/nginx └─31516 nginx: worker process Mar 05 05:27:15 tecmint.com systemd[1]: Starting The nginx HTTP and reverse proxy server. Mar 05 05:27:15 tecmint.com nginx[31509]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok Mar 05 05:27:15 tecmint.com nginx[31509]: nginx: configuration file /etc/nginx/nginx.conf test is successful Mar 05 05:27:15 tecmint.com systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument Mar 05 05:27:15 tecmint.com systemd[1]: Started The nginx HTTP and reverse proxy server.
Reload Nginx Service
To tell Nginx to reload its configuration, use the following command.
$ sudo systemctl reload nginx #systemd OR $ sudo service nginx reload #sysvinit
Stop Nginx Service
If you want to stop the Nginx service for once reason or the other, use the following command.
$ sudo systemctl stop nginx #systemd OR $ sudo service nginx stop #sysvinit
Show Nginx Command Help
To get an easy reference guide of all Nginx commands and options, use following command.
systemctl [OPTIONS. ] . Query or send control commands to the systemd manager. -h --help Show this help --version Show package version --system Connect to system manager -H --host=[[email protected]]HOST Operate on remote host -M --machine=CONTAINER Operate on local container -t --type=TYPE List units of a particular type --state=STATE List units with particular LOAD or SUB or ACTIVE state -p --property=NAME Show only properties by this name -a --all Show all loaded units/properties, including dead/empty ones. To list all units installed on the system, use the 'list-unit-files' command instead. -l --full Don't ellipsize unit names on output -r --recursive Show unit list of host and local containers --reverse Show reverse dependencies with 'list-dependencies' --job-mode=MODE Specify how to deal with already queued jobs, when queueing a new job --show-types When showing sockets, explicitly show their type -i --ignore-inhibitors .
You might also like to read these following Nginx related articles.
That’s all for now! In this guide, we have explained some of the most commonly used Nginx service management commands that you should know, including starting, enabling, restarting and stopping Nginx. If you have any additions or questions to ask, use the feedback form below.
Проверка конфигурации и перезапуск Nginx
Перед перезапуском веб-сервера nginx всегда имеет смысл тестировать корректность конфигурационных файлов, при наличии ошибок nginx может не запуститься, что вызовет неработоспособность сайта или сервиса, который обслуживает веб-сервер.
Как протестировать конфигурацию и перезапустить nginx
Проверить правильность синтаксиса конфигурационных файлов можно выполнив следующую команду
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Результат приведен на скриншоте:
При положительном результате в выводе будет приведенное выше сообщение или Syntax OK в зависимости от версии пакета. Если найдены ошибки выведутся названия файлов и строки на которых ошибки обнаружены.
Похожим образом тестируется конфигурация Apache (apache2ctl -t)
После тестирования серверу необходимо дать команду на перечитывание конфигурационных файлов (опция -s обозначает signal, серверу можно отправить множество сигналом, но чаще всего это reload, stop и start)
Если ошибки все же есть и конфиги предварительно не тестировались nginx -s reload перезапустит nginx только в случае если к остановке веб-сервера это не приведет, т.е. если серьезных ошибок в конфигурации нет
Чтобы выполнить полную перезагрузку необходимо выполнить
либо через systemctl, более современный способ управления сервисами
Конфигурационные файлы при этом не тестируются. Выполнение команды необходимо при внесении каких-либо существенных изменений когда простого reload недостаточно.
Если Nginx по какой-то причине не останавливается (т.е. после выполнения /etc/init.d/nginx stop в выводе ps aux | grep nginx остаются процессы) процессы требуется завершить вручную, затем запустить Nginx.
Такое бывает если пакет собирался из исходников и для него не написаны инициализационные скрипты.
Здесь /usr/sbin/nginx это стандартный полный путь к бинарному файлу nginx, бинарный файл может находиться в другом месте. Откуда запущен процесс можно увидеть выполнив ps auxf| grep nginx перед завершением процесса.
При работе в нагруженных проектах, обслуживающих сайты с высокой посещаемостью NGINX конфигурируют специальным образом, что дает максимальную производительность. Для небольших проектов выполнить такие настройки тоже может оказаться полезно.