- nginx под Windows
- nginx for Windows
- Running Nginx on Bash for Windows 10
- CommandLine
- Starting, Stopping, and Restarting NGINXВ¶
- Starting NGINXВ¶
- Basic Example of Starting NGINXВ¶
- Advanced Example of Starting NGINXВ¶
- OptionsВ¶
- Stopping or Restarting NGINXВ¶
- Loading a New Configuration Using SignalsВ¶
- Upgrading To a New Binary On The FlyВ¶
- Nginx configuration setup for windows
- 2 Answers 2
nginx под Windows
Версия nginx под Windows использует “родной” Win32 API (не эмуляцию Cygwin). В настоящий момент в качестве методов обработки соединений используются select() и poll() (1.15.9), поэтому не стоит ожидать высокой производительности и масштабируемости. В силу этого и ряда других известных проблем версия nginx под Windows рассматривается пока как бета-версия. На данный момент в ней доступна практически вся функциональность, что и в версии nginx под UNIX, за исключением XSLT-фильтра, фильтра изображений, модуля GeoIP и встроенного языка Perl.
Чтобы установить nginx/Windows, скачайте дистрибутив последней основной версии (1.19.10), поскольку основная ветвь nginx содержит все известные исправления. Затем распакуйте дистрибутив, перейдите в каталог nginx-1.19.10 и запустите nginx . Вот пример для корневого каталога на диске C:
Чтобы увидеть процессы nginx, запустите утилиту командной строки tasklist :
Один из процессов главный, другой — рабочий. Если nginx не запускается, нужно искать причину в в файле лога ошибок logs\error.log . Если же лог-файл не создался, то причину этого следует искать в Windows Event Log. Если вместо ожидаемой страницы выводится страница с ошибкой, нужно также искать причины ошибки в файле logs\error.log .
nginx/Windows использует каталог, в котором он был запущен, в качестве префикса для относительных путей в конфигурации. В вышеприведённом примере префиксом является C:\nginx-1.19.10\ . Пути в конфигурационном файле должны задаваться в UNIX-стиле с использованием прямых слэшей:
nginx/Windows работает как стандартное консольное приложение (не сервис) и управляется при помощи следующих команд:
nginx for Windows
Version of nginx for Windows uses the native Win32 API (not the Cygwin emulation layer). Only the select() and poll() (1.15.9) connection processing methods are currently used, so high performance and scalability should not be expected. Due to this and some other known issues version of nginx for Windows is considered to be a beta version. At this time, it provides almost the same functionality as a UNIX version of nginx except for XSLT filter, image filter, GeoIP module, and embedded Perl language.
To install nginx/Windows, download the latest mainline version distribution (1.19.10), since the mainline branch of nginx contains all known fixes. Then unpack the distribution, go to the nginx-1.19.10 directory, and run nginx . Here is an example for the drive C: root directory:
Run the tasklist command-line utility to see nginx processes:
One of the processes is the master process and another is the worker process. If nginx does not start, look for the reason in the error log file logs\error.log . If the log file has not been created, the reason for this should be reported in the Windows Event Log. If an error page is displayed instead of the expected page, also look for the reason in the logs\error.log file.
nginx/Windows uses the directory where it has been run as the prefix for relative paths in the configuration. In the example above, the prefix is C:\nginx-1.19.10\ . Paths in a configuration file must be specified in UNIX-style using forward slashes:
nginx/Windows runs as a standard console application (not a service), and it can be managed using the following commands:
Running Nginx on Bash for Windows 10
Posted 24 June, 2016
I normally go for Apache as my go-to webserver, lately however I got a liking to Nginx, for no real reasons except for the fact it has a nicer config layout. (a bad reason is a reason non the less) So when I installed Bash for Windows 10, I when and tried Nginx, sadly it didn’t work, and still doesn’t work nicely. I however got it running, this is how : First, install Nginx.
Then I wanted to ignite Nginx, but that did not work, starting Nginx failed cause of port 80 was in use.
Since I am running two systems (Linux and Windows 10) there are plenty of places to look. I started with the location I know best and was most unlikely the problem : Linux. Using netstat -tulpn | grep 80 I verified nothing was running on this freshly installed UbuntuBash. So onto W10, I know Skype, Apache, … uses port 80, but that did not run, so the hunt continued. I finally found -using resmon.exe – under Listener-port the problem, port 80 was being used by System (PID 4) … not something you can easily kill …
PID 4 (Sytem) was listening on port 80. (no longer seen here)
I dug a bit further and found this useful post. You have to stop some service, this is done using :
- windows key + x
- select console (admin)
- run net stop http
net stop http in Windows 10 (in dutch)
After that I retried nginx to once again be shown an error :
That was solved using this -still open- bugreport on github. The essence is add the following to /etc/nginx/nginx.conf :
Now to be honest I have got no idea, what any of those parameters do. (note) I tried w/o the daemon parameter and it works as well, so I only use master_process and everything seems to “work”. (different from the solution on github!)
After this, Nginx is running nicely on my BashOnWindows. Pretty nice work, Windows !
On my second machine I also had to change /etc/nginx/sites-available/default the following line :
This probably cause some ipv6 problem. (this is development only anyway!)
CommandLine
Starting, Stopping, and Restarting NGINXВ¶
This page shows you how to start NGINX, and once it’s running, how to control it so that it will stop or restart.
Starting NGINXВ¶
NGINX is invoked from the command line, usually from /usr/bin/nginx .
Basic Example of Starting NGINXВ¶
Advanced Example of Starting NGINXВ¶
OptionsВ¶
-?, -h | Print help. |
-v | Print version. |
-V | Print NGINX version, compiler version and configure parameters. |
-t | Don’t run, just test the configuration file. NGINX checks configuration for correct syntax and then try to open files referred in configuration. |
-q | Suppress non-error messages during configuration testing. |
-s signal | Send signal to a master process: stop, quit, reopen, reload. (version >= 0.7.53) |
-p prefix | Set prefix path (default: /usr/local/nginx/ ). (version >= 0.7.53) |
-c filename | Specify which configuration file NGINX should use instead of the default. |
-g directives | Set global directives. (version >= 0.7.4) |
NGINX has only a few command-line parameters. Unlike many other software systems, the configuration is done entirely via the configuration file (imagine that).
Stopping or Restarting NGINXВ¶
There are two ways to control NGINX once it’s already running. The first is to call NGINX again with the -s command line parameter. For example, /usr/bin/nginx -s stop will stop the NGINX server. (other -s options are given in the previous section)
The second way to control NGINX is to send a signal to the NGINX master process. By default NGINX writes its master process id to /usr/local/nginx/logs/nginx.pid . You can change this by passing parameter with ./configure at compile-time or by using pid directive in the configuration file.
Here’s how to send the QUIT (Graceful Shutdown) signal to the NGINX master process:
The master process can handle the following signals:
TERM, INT | Quick shutdown |
QUIT | Graceful shutdown |
KILL | Halts a stubborn process |
HUP | |
USR1 | Reopen the log files |
USR2 | Upgrade Executable on the fly |
WINCH | Gracefully shutdown the worker processes |
There’s no need to control the worker processes yourself. However, they support some signals, too:
TERM, INT | Quick shutdown |
QUIT | Graceful shutdown |
USR1 | Reopen the log files |
Loading a New Configuration Using SignalsВ¶
NGINX supports a few signals that you can use to control it’s operation while it’s running.
The most common of these is 15, which just stops the running process:
The more interesting option however, is being able to change the NGINX configuration on the fly (notice that we test the configuration prior to reloading it):
What happens is that when NGINX receives the HUP signal, it tries to parse the configuration file (the specified one, if present, otherwise the default), and if successful, tries to apply a new configuration (i.e. re-open the log files and listen sockets). If successful, NGINX runs new worker processes and signals graceful shutdown to old workers. Notified workers close listen sockets but continue to serve current clients. After serving all clients old workers shutdown. If NGINX couldn’t successfully apply the new configuration, it continues to work with an old configuration.
RequestForReviewCategory – (Request For Review: Just What Happens With The Worker Processes at a HUP? -Olle)
Upgrading To a New Binary On The FlyВ¶
If you need to replace NGINX binary with a new one (when upgrading to a new version or adding/removing server modules), you can do it without any service downtime — no incoming requests will be lost.
First, replace old binary with a new one, then send USR2 signal to the master process. It renames its .pid file to .oldbin (e.g. /usr/local/nginx/logs/nginx.pid.oldbin ), then executes a new binary, which in turn starts a new master process and the new worker processes:
At this point, two instances of NGINX are running, handling the incoming requests together. To phase the old instance out, you have to send WINCH signal to the old master process, and its worker processes will start to gracefully shut down:
After some time, old worker processes all quit and only new worker processes are handling the incoming requests:
At this point you can still revert to the old server because it hasn’t closed its listen sockets yet, by following these steps:
- Send HUP signal to the old master process — it will start the worker processes without reloading a configuration file
- Send QUIT signal to the new master process to gracefully shut down its worker processes
- Send TERM signal to the new master process to force it quit
- If for some reason new worker processes do not quit, send KILL signal to them
After new master process quits, the old master process removes .oldbin suffix from its .pid file, and everything is exactly as before the upgrade attempt.
If an update is successful and you want to keep the new server, send QUIT signal to the old master process to leave only new server running:
Nginx configuration setup for windows
I am trying to run my vue applications trough nginx on windows and i was using the following tutorials, one to run nginx with AlwaysUp and the other one to configure it.
I also stumbled upon the following stack overflow question which is basically the problem i have but it didnt work:
The service is running and recognizes the two domains i am trying to set up but for whatever reason it always sends me back to the NGINX Welcome page and i am not sure what i am doing wrong.
I followed the steps on the second tutorial and did a few changes, such ass adding «server_names_hash_bucket_size 64;» to my nginx.config file. I also created the symlink between the «sites-available» and «sites-enabled directories» using windows mklink.
Here are my files.
My app config file in sites-available which also contains a symlink in sites-enabled:
2 Answers 2
I also faced the issue how to kill the nginx process. I stumbled a while until I came up with the following command which works:
Well, after many hours i actually found out what was happening. Everything in my files, from the nginx.conf file to every other .conf files were ok.
However i discovered that when restarting or stop/starting my nginx service with either the AlwaysUp program or the windows service options the service would still be active somehow and wouldnt apply my changes, therefore it would always show me the «welcome to nginx» page.
So i just restarted my computer because i wasnt able to kill the service with conventional means and it worked just fine for every single app i have.
I am sure there is a better way to kill the service and restart it but restarting my computer so the changes to my files would actually be applied solved it.
EDIT: I also discovered that windows takes a little while to stop the nginx service, so if you are using always up try stopping the service there, if it fails try stopping the service trough windows services menu. Also don’t forget to set it to manual so you wont accidentally access you nginx app instead of your actual deployed app.