Distributed - Server Nginx: Introduction to Nginx in the Basic Series | Download and Installation | Start and Stop the Service

01. Introduction to Nginx

Nginx is a high-performance web server and a reverse proxy server. It was originally developed to solve the C10K problem, which is how to have a server handle thousands of concurrent connections at the same time. Nginx adopts an event-driven asynchronous non-blocking processing method and can efficiently handle a large number of concurrent connections, so it is widely used in high-concurrency web application scenarios.

In addition, Nginx can also serve as a POP3/SMTP/IMAP proxy server to proxy mail server requests and responses. This allows Nginx to run multiple services on one server at the same time, improving server utilization.

02. Forward proxy and reverse proxy

Forward proxy and reverse proxy are two different proxy modes with different functions and implementation methods.

Forward Proxy is a way for clients to access Internet resources through a proxy server. In this mode, the client sends a request to the proxy server, and the proxy server forwards the request to the server on the Internet, and finally returns the response to the client. The function of the forward proxy is to hide the client's real IP address, protect the client's privacy, speed up access, cache commonly used resources, etc.

Reverse proxy (Reverse Proxy) is a way for the server to provide services to the client through a proxy server. In this mode, the client sends a request to the proxy server, and the proxy server forwards the request to a server in the back-end server cluster based on the content of the request, and finally returns the response result to the client. The function of a reverse proxy is to hide the real IP address of the back-end server and improve the security of the system. At the same time, it can realize load balancing, cache acceleration, SSL/TLS encryption and other functions.

In general, forward proxy means that the client accesses Internet resources through the proxy server, and reverse proxy means that the server provides services to the client through the proxy server. The functions and implementation methods of the two are different, but both can improve the security and performance of the system.

03. The differences between Nginx, Apache and Tomcat

Nginx, Apache and Tomcat are all common web servers. They have the following differences:

① Different design concepts: Nginx uses event-driven asynchronous non-blocking processing, which can efficiently handle a large number of concurrent connections; Apache uses a multi-process or multi-thread method to process requests, which is suitable for processing static resources; Tomcat is a Java Servlet container, mainly Used to handle dynamic web applications.

② Different functions: Nginx is mainly used for reverse proxy, load balancing, static file service, SSL/TLS encryption, etc.; Apache, in addition to supporting reverse proxy and load balancing, also supports dynamic content generation, modular expansion, etc.; Tomcat is A complete Java Web application server that supports technologies such as Java Servlet and JavaServer Pages (JSP).

③ Different configuration methods: Nginx’s configuration file uses syntax similar to programming languages, and the configuration is simple and flexible; Apache’s configuration file uses XML-based syntax, and the configuration is relatively complex; Tomcat’s configuration file uses XML-based syntax, and the configuration is relatively simple.

④ Different performance: Nginx performs well in high-concurrency Web application scenarios and can efficiently handle a large number of concurrent connections; Apache performs well in processing static resources, but has poor performance in high-concurrency scenarios; Tomcat performs well in processing dynamic Web applications The performance is excellent, but the performance is also poor in high concurrency scenarios.

To sum up, Nginx, Apache and Tomcat all have their own advantages and disadvantages. Which web server to choose depends on the specific application scenarios and needs.

04. Advantages of Nginx

Nginx has the following main advantages:

① High performance: Nginx adopts event-driven asynchronous non-blocking processing and can efficiently handle a large number of concurrent connections. Its design goal is to solve the C10K problem, be able to handle thousands of concurrent connections, and is suitable for high-concurrency web application scenarios.

② Low resource consumption: Compared with the traditional multi-threading model, Nginx's process and thread model are lighter and occupy less system resources. It can handle more concurrent requests with less memory and CPU resources, improving server utilization.

③ High reliability: Nginx has good stability and reliability. It can handle abnormal situations, such as network failures, back-end server downtime, etc., and provides a robust error handling mechanism. In addition, Nginx also supports hot deployment, which allows configuration and software updates without interrupting service.

④ Flexible configuration and scalability: Nginx’s configuration file adopts a syntax similar to that of a programming language, making the configuration simple and flexible. It supports a modular architecture and can expand functions by loading different modules, such as reverse proxy, load balancing, cache acceleration, SSL/TLS encryption, etc.

⑤ Supports rich functions: In addition to serving as a web server and reverse proxy server, Nginx also has other functions, such as load balancing, dynamic HTTP content caching, virtual host configuration, URL rewriting, access control, etc. These functions make Nginx suitable for various complex application scenarios.

To sum up, Nginx is favored for its high performance, low resource consumption, high reliability, flexible configuration and rich functions, and has become the preferred web server and reverse proxy server for many large websites and applications.

05. Commonly used features of Nginx

Nginx has a variety of features. Here are some commonly used features:

① Static file service: Nginx can quickly and efficiently provide access to static files, such as HTML, CSS, JavaScript, pictures, etc. It can directly respond to client requests and reduce the load on the back-end server by configuring a simple static file directory.

② Reverse proxy: Nginx can be used as a reverse proxy server to forward client requests to multiple back-end servers to achieve load balancing and high availability. It can distribute requests to different backend servers according to configured rules, improving system performance and reliability.

③ Load balancing: Nginx supports a variety of load balancing algorithms, such as polling, IP hashing, least connections, etc. By distributing requests to multiple backend servers, Nginx can balance the load on the server and improve the performance and scalability of the system.

④ Dynamic HTTP content caching: Nginx can cache dynamically generated HTTP content to reduce the load and response time of the back-end server. It can cache specific URLs or responses according to configured rules, improving system performance and response speed.

⑤ SSL/TLS encryption support: Nginx can provide a secure HTTPS connection and support the SSL/TLS protocol to protect data transmission security. It can configure and manage SSL certificates to achieve encrypted communication and security authentication.

⑥ Virtual host configuration: Nginx supports virtual host configuration and can host multiple domain names or websites on one server. By configuring different virtual hosts, Nginx can distribute requests to different websites or applications based on the requested domain name.

⑦ URL rewriting and redirection: Nginx can implement URL rewriting and redirection by configuring URL rewriting rules. It can modify the requested URL to achieve friendly URL structure and search engine optimization.

⑧ Access control and security: Nginx supports access control based on IP address, user agent, request method, etc., and can restrict specific clients or requests. It also supports security features such as preventing malicious requests, DDoS attacks, etc.

In addition to the above functions, Nginx also supports HTTP/2 protocol, WebSocket protocol, gzip compression, logging, HTTP authentication, etc. These features make Nginx a powerful and flexible web server and reverse proxy server.

06. Nginx download

① The official website of Nginx is: http://nginx.org

② The official download website of Nginx is: http://nginx.org/en/download.html

③ Obtain Nginx source code: http://nginx.org/download/

07. Nginx installation

There are two ways to install Nginx:

  • Simple installation through Nginx source code (1)
  • Install via yum(2)
  • Complex installation through Nginx source code (3)

1. Environment preparation before source code installation

① Install GCC

Nginx is a program written in C language, so if you want to run Nginx, you need to install a compilation tool. GCC is a collection of open source compilers used to process a variety of languages, including the C language.

# 安装
[root@192 ~]# yum install -y gcc
# 查看是否安装成功
[root@192 ~]# gcc --version

② Install PCRE

Nginx needs to use the PCRE library (perl Compatible Regular Expressoin compatible regular expression library) during the compilation process, because both the Rewrite module and the http core module of Nginx use PCRE regular expression syntax.

# 安装
[root@192 ~]# yum install -y pcre pcre-devel
# 查看是否安装成功
[root@192 ~]# rpm -qa pcre pcre-devel

③ Install zlib

The zlib library provides developers' compression algorithm. Gzip compression needs to be used in each module of Nginx, so we also need to install its library and source code zlib and zlib-devel in advance.

# 安装
[root@192 ~]# yum install -y zlib zlib-devel
# 查看是否安装成功
[root@192 ~]# rpm -qa zlib zlib-devel

④ OpenSSL

OpenSSL is an open source software library package that applications can use to communicate securely and avoid eavesdropping.

SSL: The abbreviation of Secure Sockets Layer protocol can provide confidential transmission on the Internet. Its goal is to ensure the confidentiality and reliability of communication between two applications. In Nginx, if the server needs to provide secure web pages, it needs to use the OpenSSL library, so we need to install the OpenSSL library file and its development installation package.

# 安装
[root@192 ~]# yum install -y openssl openssl-devel
# 查看是否安装成功
[root@192 ~]# rpm -qa openssl openssl-devel

⑤ It would be troublesome to do the above commands one by one. We can also install them with one command.

[root@192 ~]# yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel

2. Simple installation method of Nginx source code

① Enter the official website to find the link address of the version you want to download, and then use the wget command to download it.

[root@192 ~]# wget http://nginx.org/download/nginx-1.16.1.tar.gz

② Package the downloaded resources and place the downloaded resources in the directory nginx/core

[root@192 ~]# mkdir -p nginx/core
[root@192 ~]# mv nginx-1.16.1.tar.gz nginx/core
[root@192 ~]# cd nginx/core

③ Decompress

[root@192 core]# tar -xzf nginx-1.16.1.tar.gz
[root@192 core]# ls
nginx-1.16.1  nginx-1.16.1.tar.gz

④ Enter the resource file and find configure

[root@192 core]# cd nginx-1.16.1
[root@192 nginx-1.16.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@192 nginx-1.16.1]# ./configure

Insert image description here

⑤ Compile and install

[root@192 nginx-1.16.1]# make && make install

⑥ View the nginx installation directory:

[root@192 nginx-1.16.1]# cd /usr/local/nginx/
[root@192 nginx]# ll
drwx------. 2 nobody root    6 412 07:23 client_body_temp
drwxr-xr-x. 2 root   root 4096 86 16:43 conf
drwx------. 2 nobody root    6 412 07:23 fastcgi_temp
drwxr-xr-x. 2 root   root   40 412 07:19 html
drwxr-xr-x. 2 root   root   58 828 22:00 logs
drwx------. 2 nobody root    6 412 07:23 proxy_temp
drwxr-xr-x. 2 root   root   36 828 22:18 sbin
drwx------. 2 nobody root    6 412 07:23 scgi_temp
drwx------. 2 nobody root    6 412 07:23 uwsgi_temp
[root@192 nginx]#

⑦ Start nginx:

[root@192 nginx]# cd sbin
[root@192 sbin]# ll
-rwxr-xr-x  1 root root 3825520 828 22:18 nginx
-rwxr-xr-x. 1 root root 3892016 412 07:20 nginx.old
[root@192 sbin]# ./nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

⑧ You can see that the startup error is reported because port 80 is occupied because I have installed and started nginx before.

# 查找占用80端口的进程
[root@192 sbin]# lsof -i :80
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   1075   root    6u  IPv4  29234      0t0  TCP *:http (LISTEN)
nginx   1078 nobody    6u  IPv4  29234      0t0  TCP *:http (LISTEN)
# 停止占用80端口的进程
[root@192 sbin]# kill -9 1075
[root@192 sbin]# sudo lsof -i :80

⑨ Restart nginx:

[root@192 sbin]# ./nginx
[root@192 sbin]# sudo lsof -i :80
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   6484   root    6u  IPv4  67768      0t0  TCP *:http (LISTEN)
nginx   6485 nobody    6u  IPv4  67768      0t0  TCP *:http (LISTEN)

Check whether the nginx welcome page is accessible:

Insert image description here

3. Nginx yum installation method

Yum installation tutorial provided by Nginx official website: http://nginx.org/en/linux_packages.html#RHEL

① Install yum-utils

[root@192 sbin]# sudo yum  install -y yum-utils

② Add yum source file

[root@192 sbin]# vi /etc/yum.repos.d/nginx.repo
[root@192 sbin]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

③ Use yum to install

[root@192 sbin]# yum install -y nginx

④ Check the installation location of nginx

[root@192 sbin]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/local/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz

⑥ Start the test:

[root@192 sbin]# cd /usr/sbin
[root@192 sbin]# ./nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
[root@192 sbin]# sudo lsof -i :80
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   6484   root    6u  IPv4  67768      0t0  TCP *:http (LISTEN)
nginx   6485 nobody    6u  IPv4  67768      0t0  TCP *:http (LISTEN)
[root@192 sbin]# kill -9 6484
[root@192 sbin]# kill -9 6485
[root@192 sbin]# sudo lsof -i :80
[root@192 sbin]# ./nginx

Insert image description here

4. Complex installation method of Nginx source code

① Enter the installation directory for simple installation:

[root@192 nginx-1.16.1]# pwd
/root/nginx/core/nginx-1.16.1
[root@192 nginx-1.16.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
[root@192 nginx-1.16.1]# ./configure --help

Insert image description here

② The difference between complex installation methods and simple installation configurations is in the first step. To ./configureset the compilation parameters, we need to specify them manually and understand some simple PATH path configurations:

  • –prefix=PATH: points to the Nginx installation directory, the default value is /usr/local/nginx

  • –sbin-path=PATH: The path pointing to (execution) program file (nginx), the default value is /sbin/nginx

  • –modules-path=PATH: points to the Nginx dynamic module installation directory, the default value is /modules

  • –conf-path=PATH: The path to the configuration file (nginx.conf), the default value is /conf/nginx.conf

  • –error-log-path=PATH: path to the error log file, the default value is /logs/error.log

  • –http-log-path=PATH: The path to the access log file, the default value is /logs/access.log

  • –pid-path=PATH: Points to the file path for ID after Nginx is started. The default value is /logs/nginx.pid

  • –lock-path=PATH: Points to the storage path of the Nginx lock file. The default value is /logs/nginx.lock

③ Uninstall nginx that has been installed on the previous server. The uninstallation process is divided into three steps:

# 需要将nginx的进程关闭
[root@192 nginx-1.16.1]# cd /usr/local/nginx/sbin
[root@192 sbin]# ./nginx -s stop
# 将安装的nginx进行删除
[root@192 sbin]# rm -rf /usr/local/nginx
# 将安装包之前编译的环境清除掉
[root@192 usr]# cd ~/nginx/core/nginx-1.16.1
[root@192 nginx-1.16.1]# make clean
rm -rf Makefile objs

./configureSet the compilation parameters through:

[root@192 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx \
> --sbin-path=/usr/local/nginx/sbin/nginx \
> --modules-path=/usr/local/nginx/modules \
> --conf-path=/usr/local/nginx/conf/nginx.conf \
> --error-log-path=/usr/local/nginx/logs/error.log \
> --http-log-path=/usr/local/nginx/logs/access.log \
> --pid-path=/usr/local/nginx/logs/nginx.pid \
> --lock-path=/usr/local/nginx/logs/nginx.lock

[root@192 nginx-1.16.1]# make && make install

⑤ Start the test:

[root@192 nginx]# cd /usr/local/nginx/sbin
[root@192 sbin]# ./nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
[root@192 sbin]# lsof -i :80
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   7638  root    6u  IPv4  75732      0t0  TCP *:http (LISTEN)
nginx   7639 nginx    6u  IPv4  75732      0t0  TCP *:http (LISTEN)
[root@192 sbin]# kill -9 7638
[root@192 sbin]# kill -9 7639
[root@192 sbin]# ./nginx
[root@192 sbin]# ./nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
configure arguments: --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock

Insert image description here

08. Nginx directory structure analysis

Install the tree tool through yum install -y treehere. Through tree, we can view the file directory structure on the centos system in a comprehensive way:

[root@192 sbin]# tree /usr/local/nginx/
/usr/local/nginx/
├── client_body_temp
├── conf
│   ├── fastcgi.conf
│   ├── fastcgi.conf.default
│   ├── fastcgi_params
│   ├── fastcgi_params.default
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types
│   ├── mime.types.default
│   ├── nginx.conf
│   ├── nginx.conf.default
│   ├── scgi_params
│   ├── scgi_params.default
│   ├── uwsgi_params
│   ├── uwsgi_params.default
│   └── win-utf
├── fastcgi_temp
├── html
│   ├── 50x.html
│   └── index.html
├── logs
│   ├── access.log
│   ├── error.log
│   └── nginx.pid
├── proxy_temp
├── sbin
│   └── nginx
├── scgi_temp
└── uwsgi_temp

① conf: directory of all nginx configuration files

cgi (Common Gateway Interface) is a universal gateway [interface] that mainly solves the problem of sending a request and data from the client. After the server obtains the request and data, it can call the CGI [program] to process and send the corresponding results to the client. Standard specifications.

  • fastcgi.conf: fastcgi related configuration file
  • fastcgi.conf.default: backup file of fastcgi.conf
  • fastcgi_params: fastcgi parameter file
  • fastcgi_params.default: fastcgi parameter backup file
  • scgi_params: scgi parameter file
  • scgi_params.default: scgi parameter backup file
  • uwsgi_params: uwsgi parameter file
  • uwsgi_params.default: uwsgi parameter backup file
  • mime.types: records the corresponding relationship between the Content-Type value in the HTTP protocol and the file suffix name.
  • mime.types.default: backup file of mime.types
  • nginx.conf: This is the core configuration file of Nginx
  • nginx.conf.default: backup file of nginx.conf

② html: stores the two static html pages that come with nginx

  • 50x.html: Failure page after access failure
  • index.html: The default home page for successful access

③ Logs: The file that records the entry. When the nginx server is started, there will be three files: access.log error.log and nginx.pid.

# 查看nginx的错误日志
[root@192 sbin]# tail -f /usr/local/nginx/logs/error.log
2023/08/29 21:21:37 [error] 11898#0: *1 open() "/usr/local/nginx/html/acv" failed (2: No such file or directory), client: 192.168.38.1, server: localhost, request: "GET /acv HTTP/1.1", host: "192.168.38.33"

④ sbin: The directory where the nginx executable file is located. You can start, stop and restart the Nginx server through this file.

09. Nginx server start and stop commands

1. Signals control the starting and stopping of the Nginx server

After the Nginx installation is complete, next we need to look at how to start, restart and stop the Nginx service. There are many ways to start and stop Nginx in Linux systems. There are two main ways: signal control of Nginx service and Nginx command line control.

① The master and worker processes in Nginx?

Nginx works in a multi-process mode by default. The Nginx background process contains a master process and multiple worker processes. The master process is mainly used to manage the worker processes, including receiving external information and sending the received signals to Each worker process monitors the status of the worker process. When the worker process exits abnormally, a new worker process will be automatically restarted. The worker process is specially used to process user requests. Each worker process is independent. There is no shared memory between them and they will not interfere with each other. Each worker process processes a portion of the client request and then returns the processing results to the client.

After starting Nginx, we ps -ef | grep nginxcan view the following content through the command:

[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      67744      1  0 21:27 ?        00:00:00 nginx: master process ./nginx
nobody    67745  67744  0 21:27 ?        00:00:00 nginx: worker process
root      67777   2727  0 21:27 pts/0    00:00:00 grep --color=auto nginx

The process model of nginx can be illustrated by the following figure:

Insert image description here

As an administrator, you only need to control Nginx by sending a signal to the master process. At this time, we need two prerequisites, one is the master process to be operated, and the other is the signal.

② How to get the PID of the nginx master process?

If you want to operate the Nginx master process, you need to obtain the process number ID of the master process, which can be obtained in the following two ways:

(1) ps -ef | grep nginxObtain through command:

[root@192 sbin]# ps -ef | grep nginx
root      67744      1  0 21:27 ?        00:00:00 nginx: master process ./nginx
nobody    67745  67744  0 21:27 ?        00:00:00 nginx: worker process
root      67777   2727  0 21:27 pts/0    00:00:00 grep --color=auto nginx

(2) Obtain the nginx master process ID by viewing the /usr/local/nginx/logs/nginx.pid file:

[root@192 sbin]# cat /usr/local/nginx/logs/nginx.pid
67744

③ What are the signals?

Nginx is a commonly used web server and reverse proxy server. It supports a variety of signals and can control the running status of Nginx by sending different signals. The following are commonly used signals:

  • TERM, INT: Shut down Nginx gracefully, waiting for the current request to be processed before shutting down.
  • QUIT: Shut down Nginx immediately without waiting for the current request to be processed.
  • HUP: Reloading the configuration file will first close the old worker process and then start the new worker process.
  • USR1: Reopen the log file and can be used for log cutting.
  • USR2: Smoothly upgrade the Nginx executable file, which can be used to update Nginx without downtime.
  • WINCH: Easily shut down old worker processes for smooth upgrade of Nginx.

You can use the kill command to send a signal to the Nginx process, where <nginx_pid> is the PID of the Nginx master process and singal is the signal:

kill singal <nginx_pid>

(1) Sending the TERM signal to the master process will shut down the Nginx service gracefully:

[root@192 sbin]# ps -ef | grep nginx
root      67744      1  0 21:27 ?        00:00:00 nginx: master process ./nginx
nobody    67745  67744  0 21:27 ?        00:00:00 nginx: worker process
root      68955   2727  0 21:57 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -TERM 67744
[root@192 sbin]# ./nginx
[root@192 sbin]# kill -TERM `cat /usr/local/nginx/logs/nginx.pid`

(2) Send the QUIT signal to the master process. The master process will control all work processes not to receive new requests. After all requests are processed, the processes will be closed.

[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      69172      1  0 22:01 ?        00:00:00 nginx: master process ./nginx
nobody    69173  69172  0 22:01 ?        00:00:00 nginx: worker process
root      69175   2727  0 22:01 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -QUIT 69172
[root@192 sbin]# ./nginx
[root@192 sbin]# kill -QUIT `cat /usr/local/nginx/logs/nginx.pid`

(3) Send the HUP signal to the master process. The master process will control the old work process to no longer receive new requests. After the request is processed, the old work process will be closed, and then the new work process will be restarted according to the nginx configuration file. process:

[root@192 sbin]# ps -ef | grep nginx
root      69262      1  0 22:03 ?        00:00:00 nginx: master process ./nginx
nobody    69263  69262  0 22:03 ?        00:00:00 nginx: worker process
root      69311   2727  0 22:05 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -HUP 69262
[root@192 sbin]# ps -ef | grep nginx
root      69262      1  0 22:03 ?        00:00:00 nginx: master process ./nginx
nobody    69318  69262  0 22:05 ?        00:00:00 nginx: worker process
root      69320   2727  0 22:05 pts/0    00:00:00 grep --color=auto nginx

You can see that the process number of the worker process has changed.

(4) Send the USR1 signal to the master process to tell Nginx to reopen the log file:

[root@192 logs]# ls
access.log  error.log  nginx.pid
[root@192 logs]# rm -rf error.log
[root@192 logs]# rm -rf access.log
[root@192 logs]# ls
nginx.pid
[root@192 logs]# kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
[root@192 logs]# ls
access.log  error.log  nginx.pid

(5) Send the WINCH signal to the master process to let the master process control not allowing all work processes to receive new requests, and close the work processes after the requests are processed. Note that the master process will not be shut down:

[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      69699      1  0 22:13 ?        00:00:00 nginx: master process ./nginx
nobody    69700  69699  0 22:13 ?        00:00:00 nginx: worker process
root      69704   2727  0 22:13 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -WINCH `cat /usr/local/nginx/logs/nginx.pid`
[root@192 sbin]# ps -ef | grep nginx
root      69699      1  0 22:13 ?        00:00:00 nginx: master process ./nginx
root      69709   2727  0 22:14 pts/0    00:00:00 grep --color=auto nginx

(6) Send the USR2 signal to the master process to tell the master process to upgrade smoothly. At this time, the corresponding master process and work process will be reopened. There will be two master processes in the entire system, and the PID of the new master process will be /usr/local/nginx/logs/nginx.pidThe PID of the old master process will be recorded in the /usr/local/nginx/logs/nginx.pid.oldbinfile, and then the QUIT signal will be sent to the old master process again to let it process the request before shutting down:

Insert image description here

[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      69968      1  0 22:20 ?        00:00:00 nginx: master process ./nginx
nobody    69969  69968  0 22:20 ?        00:00:00 nginx: worker process
root      69971   2727  0 22:20 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
[root@192 sbin]# ps -ef | grep nginx
root      69968      1  0 22:20 ?        00:00:00 nginx: master process ./nginx
nobody    69969  69968  0 22:20 ?        00:00:00 nginx: worker process
root      70009  69968  0 22:20 ?        00:00:00 nginx: master process ./nginx
nobody    70010  70009  0 22:20 ?        00:00:00 nginx: worker process
root      70014   2727  0 22:20 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# kill -QUIT 69968
[root@192 sbin]# ps -ef | grep nginx
root      70009      1  0 22:20 ?        00:00:00 nginx: master process ./nginx
nobody    70010  70009  0 22:20 ?        00:00:00 nginx: worker process
root      70056   2727  0 22:21 pts/0    00:00:00 grep --color=auto nginx

2. Command line control to start and stop the Nginx server

This method uses the executable file nginx under sbin in the Nginx installation directory to control the Nginx status. We can nginx -hcheck what parameters are available:

[root@192 sbin]# nginx -h
nginx version: nginx/1.24.0
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /etc/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

① Parameter description:

  • -? and -h: display help information

  • -v: Print version number information and exit

  • -V: Print version number information and configuration information and exit

  • -t: Test whether the nginx configuration file syntax is correct and exit

  • -T: Test whether the nginx configuration file syntax is correct and list the configuration file information used and then exit.

  • -q: Suppress non-error messages during configuration testing

  • -s: signal signal, which can be followed by:

    • stop: Quick shutdown, similar to the function of TERM/INT signal
    • quit: graceful shutdown, similar to the function of QUIT signal
    • Reopen: Similar to the role of the USR1 signal, reopen the log file
    • reload: Similar to the function of the HUP signal, reload the configuration file
  • -p: prefix, specify the prefix path of Nginx (default: /usr/local/nginx/)

  • -c: filename, specifies the Nginx configuration file path (default: conf/nginx.conf)

  • -g: Used to supplement the Nginx configuration file and specify the global configuration to be applied to the Nginx service when it is started.

② Quickly shut down and start the Nginx server:

[root@192 sbin]# ./nginx -s stop
[root@192 sbin]# ps -ef | grep nginx
root      70300   2727  0 22:27 pts/0    00:00:00 grep --color=auto nginx
[root@192 sbin]# ./nginx
[root@192 sbin]# ./nginx -s reload

③ Specify the Nginx configuration file path:

[root@192 conf]# cp nginx.conf abc.conf

# 在abc.conf中添加一行aaa,代表这个配置文件有语法错误
[root@192 conf]# vi abc.conf

# 测试指定nginx配置文件是否有语法错误,使用参数-t和-c
[root@192 sbin]# ./nginx -tc /usr/local/nginx/conf/abc.conf
nginx: [emerg] unknown directive "aaa" in /usr/local/nginx/conf/abc.conf:3
nginx: configuration file /usr/local/nginx/conf/abc.conf test failed

10. Nginx server version upgrade and new modules

If you want to update the Nginx version or apply some new modules, the simplest way is to stop the current Nginx service and then start a new Nginx service. However, this will result in users being unable to access the server for a period of time. In order to solve this problem, we need to use the smooth upgrade function provided by the Nginx server. This is also a major feature of Nginx. Using this method, Nginx can provide services uninterrupted 7*24 hours. Next we analyze the requirements:

The Nginx version was originally Nginx-1.14.2. Due to the service upgrade, the Nginx version needs to be upgraded to Nginx-1.16.1, which requires Nginx not to interrupt the service.

In order to meet the above needs, there are two solutions: zzUse Nginx service signal to complete Nginx upgrade

② Use the make command in the Nginx installation directory to complete the upgrade

1. Environment preparation

① First prepare two versions of Nginx: 1.14.2 and 1.16.1

② Use the Nginx source code installation method to successfully install version 1.14.2 and access it correctly.

# 进入安装目录
./configure
make && make install

③ Configure parameters and compile Nginx1.16.1, no installation is required.

# 进入安装目录
./configure
make 

2. Use Nginx service signal to upgrade

① Back up nginx in the sbin directory of version 1.14.2

cd /usr/local/nginx/sbin
mv nginx nginxold

② Copy the nginx file in the objs directory compiled from the Nginx1.16.1 installation directory to the original /usr/local/nginx/sbindirectory .

cd ~/nginx/core/nginx-1.16.1/objs
cp nginx /usr/local/nginx/sbin

③ Send signal USR2 to the master process corresponding to Nginx version 1.14.2

④ Send signal QUIT to the master process corresponding to Nginx version 1.14.2

kill -QUIT `more /usr/local/logs/nginx.pid.oldbin`

3. Use the make command in the Nginx installation directory to complete the upgrade.

① Back up nginx in the sbin directory of version 1.14.2

cd /usr/local/nginx/sbin
mv nginx nginxold

② Copy the nginx file in the objs directory compiled from the Nginx1.16.1 installation directory to the original /usr/local/nginx/sbindirectory .

cd ~/nginx/core/nginx-1.16.1/objs
cp nginx /usr/local/nginx/sbin

③ Enter the installation directory and executemake upgrade

Insert image description here

④ Check whether the update is successful

./nginx -v

Throughout the entire process, Nginx has actually been providing services to the outside world. And when the Nginx server is started successfully, we can access it directly through the browser. At the same time, we can modify the content we see on the page by changing the page in the html directory.

Guess you like

Origin blog.csdn.net/qq_42764468/article/details/132550388