Nginx introduction and installation

Nginx ( engine _ _ The server can support 30,000~50,000 concurrent requests) Compared with apache, the concurrent requests are not as high as nginx , and apache’s concurrency is around 20,000

Nginx application scenarios (or functions)
Static processing: Both httpd and nginx can only handle static pages by default
Reverse proxy: do not directly process client requests, but transfer the requests to other servers
Load balancing: combined with reverse proxy , responsible for transferring the client's request to other servers with less pressure.
Resource caching: caching the data frequently accessed by the client, thereby speeding up the client's access.
Security protection: nginx has certain protective measures for itself.
Access restrictions: similar For apache's order deny, allow
access authentication: add username and password to the website visited

1. Introduction to I/O (input/output)

Each I/O goes through two stages:
1. Load the data from the disk file to the kernel space (buffer) first, and wait for the data preparation to be completed, which takes a long time.
2. Copy the data from the kernel buffer to the user space. In the memory of the process, the time is shorter

Synchronous/asynchronous attention is the callee message communication mechanism

Synchronous: The caller waits for the callee to return a message before continuing execution.
For example: the boss assigns you a task and keeps asking you if it has been completed. After completing the boss, do the next thing. This communication mechanism becomes synchronous and
asynchronous: the callee passes The status, notification or callback mechanism actively notifies the callee of the running status
. For example: the boss assigns you a task, and you will report the task progress status to the boss. The boss does his own thing and will not ask you for the results.

The difference between synchronous and asynchronous
Synchronize The callee will not return the status of the task, and the caller needs to keep asking.
asynchronous The callee will return the status of the task to the caller without the caller constantly asking.

Blocking/non-blocking: focus on the state of the caller before waiting for the result to be returned

Blocking: means that the I/O operation needs to be completely completed before returning to the user space. Before the call result is returned, the caller is suspended.
For example: washing clothes by hand, you are occupied until the washing is completed.
Non-blocking (nobloking): means that the I/O operation returns to a user state immediately after being called, without waiting for the IO operation to be completely completed. The caller will not be suspended before the final call result is returned. For example: a fully automatic washing machine, which does not need to be
occupied . You will be notified when the laundry is done. During this period, you will not be occupied by washing clothes.

I/O models include: synchronous blocking, synchronous non-blocking, asynchronous blocking (IO multiplexing select), asynchronous semi-blocking (signal-driven apache), asynchronous non-blocking (asynchronous IO model nginx)

2. nginx mode

nginx has two working modes: master-worker mode and single-process mode

master-worker: In this mode, after nginx starts successfully, there will be a master process and at least one worker process. The master process is responsible for processing system signals, loading configurations, and managing worker processes (starting, killing, monitoring, sending messages/signals, etc.)

Advantages of patterns
1. High stability. As long as there are worker processes alive, services can be provided. If a worker process hangs up the master process, a new worker process will be started immediately, ensuring that the number of worker processes remains unchanged and reducing the probability of service interruption.
2. With the CPU affinity configuration of Linux, you can make full use of the advantages of multi-core CPUs and improve performance.
3. When processing signals/configuration reloading/upgrading, it can be done with as little or no service interruption as possible.

Single process mode: There is only one process after nginx starts, and this process is responsible for all the work of nginx . Since there is only one process, it can be easily debugged using tools such as gdb . This mode does not support the smooth upgrade function of nginx . Any signal processing may cause service interruption. Since it is a single process, after the process hangs, the service cannot be restarted without external monitoring. Therefore, this mode is generally only used during the development phase and debugging, and will not be used in the production environment.

3. Installation of nginx

Installation method one: Network yum installation

Ensure that you can ping the external network

[root@C7--01 ~]# ping www.baidu.com
PING www.a.shifen.com (183.232.231.174) 56(84) bytes of data.
64 bytes from ptr.cq.chinamobile.com (183.232.231.174): icmp_seq=1 ttl=51 time=380 ms
64 bytes from ptr.cq.chinamobile.com (183.232.231.174): icmp_seq=2 ttl=51 time=114 ms
64 bytes from ptr.cq.chinamobile.com (183.232.231.174): icmp_seq=3 ttl=51 time=106 ms
64 bytes from ptr.cq.chinamobile.com (183.232.231.174): icmp_seq=4 ttl=51 time=108 ms

In:nginx:linox package website can be installed using web yum:

img

The installation process can be completed by following the steps above

img

Start command: nginx

Check the port after installation is complete

Installation method two: source code installation; download the nginx software package from the official website

Official website path: nginx: download nginx: download nginx: download

img

Download nginx-1.18.0 version this time

Upload nginx-1.18.0.tar.gz package

[root@C7--01 ~]# yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel   #安装相关软件包
[root@C7--01 ~]# ls           
anaconda-ks.cfg  nginx-1.18.0.tar.gz  yum.sh            
 
[root@C7--01 ~]# useradd -M -s /sbin/nologin nginx              
 
[root@C7--01 ~]# tar -zxvf /root/nginx-1.18.0.tar.gz -C /usr/src                     
......
...
[root@C7--01 ~]# cd /usr/src/nginx-1.18.0/
[root@C7--01 nginx-1.18.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module --with-http_dav_module --with-http_addition_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-http_ssl_module --with-http_gzip_static_module                                      
........
....
[root@C7--01 nginx-1.18.0]# make && make install                      
....
..
.
[root@C7--01 nginx-1.18.0]# /usr/local/nginx/sbin/nginx -t               #测试安装是否成功
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
 
[root@C7--01 nginx-1.18.0]# /usr/local/nginx/sbin/nginx                   #启动
 
 
[root@C7--01 nginx-1.18.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/                           

access

img

The installation is complete

4. Introduction and operation of nginx configuration file

Note: Different installation methods and paths are different.

What is the directory structure of Nginx?

tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf # Nginx所有配置文件的目录
│ ├── fastcgi.conf # fastcgi相关参数的配置文件
│ ├── fastcgi.conf.default         # fastcgi.conf的原始备份文件
│ ├── fastcgi_params # fastcgi的参数文件
│ ├── fastcgi_params.default       
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types # 媒体类型
│ ├── mime.types.default
│ ├── nginx.conf # Nginx主配置文件
│ ├── nginx.conf.default
│ ├── scgi_params # scgi相关参数文件
│ ├── scgi_params.default  
│ ├── uwsgi_params # uwsgi相关参数文件
│ ├── uwsgi_params.default
│ └── win-utf
├── fastcgi_temp # fastcgi临时数据目录
├── html # Nginx默认站点目录
│ ├── 50x.html # 错误页面优雅替代显示文件,例如当出现502错误时会调用此页面
│ └── index.html # 默认的首页文件
├── logs # Nginx日志目录
│ ├── access.log # 访问日志文件
│ ├── error.log # 错误日志文件
│ └── nginx.pid # pid文件,Nginx进程启动后,会把所有进程的ID号写到此文件
├── proxy_temp # 临时目录
├── sbin # Nginx命令目录
│ └── nginx # Nginx的启动命令
├── scgi_temp # 临时目录
└── uwsgi_temp # 临时目录

1. Introduction to configuration files

module Function
main (global settings) The set directive will affect all other settings
events (nginx working mode) Set working mode and number of connections
http (http settings) Set timeout, etc. etc.
sever (host settings) Mainly used to specify the host and port
location(URL match) Used to match web page locations

1.Main is located at the highest level of the nginx.conf configuration file.
2. There can be Event and HTTP layers under the Main layer.
3. Multiple Server layers are allowed under the HTTP layer, which are used to configure different configurations for different websites.
4. Server layer Multiple Locations are also allowed

[root@C7--01 ~]# vim /usr/local/nginx/conf/nginx.conf            #进入配置文件
 
----------------------------以下是全局配置端(main)
 
 
  1 
  2 #user  nobody;                                  #设置master进程启动后,fork出的worker进程运行在哪个用户和用户组下;默认由nobody账号运行
  3 worker_processes  4(或auto);                   #指定工作衍生进程数(一般等于CPU的总核数或总核数的两倍)
    worker_cpu_affinity 0001 0010 0100 1000         #将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的
  4 worker_cpu_affinity auto                        #自动绑定设置
 
  5 #error_log  logs/error.log;                     #指定错误日志存放的路径
  6 #error_log  logs/error.log  notice;             #错误日志记录级别
  7 #er  nobody;
  8 #  3 worker_processes  1;
  9 #    4   
 10 #    rror_log  logs/error.log  info;
 11 
 12 #pid        logs/nginx.pid;                     #指定进程pid的存储文件位置
 13     
 14 worker_rlimit_nofile 512000;                    #工作进程最大打开文件数                           
 15 events {
    
                                            #事件模块
 16     use epoll;                                  #使用的网络I/O模型,Linux推荐使用epoll模式;默认为epoll模式
 17     worker_connections  1024;                   #用于定义Nginx每个进程的最大连接数,默认是1024
 18 }   
 19   
 20 http {
    
    
 21     include       mime.types;                  #导入支持的文件类型
 22     default_type  application/octet-stream;    #设置默认的类型,会提示下载不匹配的类型文件
 23 
 24     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '                   # log_format是Nginx的HttpLog模块指令,用于指定Nginx日志的输出格式。main为此日志输出格式的名称,可以在下面的access_log指令中引用
 25     #                  '$status $body_bytes_sent "$http_referer" '
 26     #                  '"$http_user_agent" "$http_x_forwarded_for"';
 27 
 28     #access_log  logs/access.log  main;
 29 
 30     sendfile        on;                                                   #用于开启高效文件传输模式。将tcp_nopush和tcp_nodelay两个指令设置为on用于防止网络阻塞
 31     #tcp_nopush     on;                                                   #在开启了sendfile的情况下,合并请求后统一发送给客户端
 32 
 33     #keepalive_timeout  0;
 34     keepalive_timeout  65;                                                #设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接;单位是秒
 35 
 36     #gzip  on;                                                            #开启文件压缩
 37 
 38     server {
    
                                             #定义作为web服务器的相关属性  可以有多个
 39         listen       80;                             #监听的端口
 40         server_name  localhost;                      #设置server name,可以以空格隔开写多个,支持正则表达式,如 *.aaa.com,www.aaa.* ~^www\d+\.aaa\.com$ default_server
 41 
 42         #charset koi8-r;                             #设置编码格式,默认是俄语格式,可以改为utf-8
 43 
 44         #access_log  logs/host.access.log  main;     #设备访问日志
 45 
 
 46         location / {
    
                                     #定义一个虚拟主机的属性,所有的web服务必须定义成一个虚拟主机
 47             root   html;                             #指定网站目录
 48             index  index.html index.htm;             #指定默认网页文件,此指令由ngx_http_index_module模块提供
 49         }
 50 
 51         #error_page  404              /404.html;
 52 
 53         # redirect server error pages to the static page /50x.html
 54         #
 55         error_page   500 502 503 504  /50x.html;     #当发生错误的时候能够显示一个预定义的uri(相对路径)
 56         location = /50x.html {
    
    
 57             root   html;
 58         }
 59 

2. nginx related operations

nginx -h                 # 查看帮助信息
 
nginx -v                 # 查看nginx版本
 
nginx start              # 启动nginx
 
nginx -s quit            # 关闭nginx,完整有序的停止nginx,保存相关信息
 
nginx -s stop            # 关闭nginx,快速停止nginx,可能不保存相关信息
 
nginx -s reload          # 重新载入nginx,当配置信息需要重新加载配置时使用
 
nginx -t -c filename     # 测试nginx配置文件是否正确
 
nginx -s reopen          # 重新打开日志文件

3. The path location of nginx installed by yum

[root@C7--01 ~]# rpm -ql nginx                               #查看所有nginx路径
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.21.4
/usr/share/doc/nginx-1.21.4/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx

Source code: The file is located wherever it is installed. You can also use the above command to view it.

4. Introduction to nginx access log

Let’s first look at http requests and returns

[root@C7--01 ~]# curl -v 192.168.2.1
* About to connect() to 192.168.2.1 port 80 (#0)            #请求行
*   Trying 192.168.2.1...
* Connected to 192.168.2.1 (192.168.2.1) port 80 (#0)       #请求头
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.2.1
> Accept: */*                                               #请求数据 
> 
< HTTP/1.1 200 OK                                           #状态码
< Server: nginx/1.18.0
< Date: Fri, 19 Nov 2021 14:48:37 GMT
< Content-Type: text/html
< Content-Length: 612
< Last-Modified: Fri, 19 Nov 2021 14:33:40 GMT
< Connection: keep-alive
< ETag: "6197b5c4-264"
< Accept-Ranges: bytes                                     #单位bytes
< 
<!DOCTYPE html>                                            #响应正文
<html> 
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
* Connection #0 to host 192.168.2.1 left intact

nginx files are a little different from apache files

The files of nginx are acces.log and error.log. The files of
apache are access_log and error_log.

[root@C7--01 ~]# vim /usr/local/nginx/conf/nginx.conf
 
 21     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 22     #                  '$status $body_bytes_sent "$http_referer" '
 23     #                  '"$http_user_agent" "$http_x_forwarded_for"';
 24 
 25     #access_log  logs/access.log  main;
 26 

The format is basically the same as apache, but nginx uses internal variables. The following is an introduction to variables.

[root@C7--01 ~]# vim /usr/lcoal/nginx/logs/access.log
 
192.168.2.1 - - [19/Nov/2021:22:48:37 +0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0"
$remote_addr Remote request IP address
Remote user mailbox By default, it is not displayed as -
$remote_user The name of the client user. If not available, replace it with -.
$time_local local timestamp
$request Request a specific URI file, such as a JPG image in a web page
$status http request status code
$body_bytes_sent Request file size
$http_refer The webpage URL jump source and source address can be forged. For example, an HTML web page then calls the image URI resource
$http_user_agent Information related to user terminal browser UserAgent
$http_x_forwarded_for It is the real IP of the HTTP requester. This item will only be added when passing the HTTP proxy or load balancing server.

Guess you like

Origin blog.csdn.net/qq_36306519/article/details/131096083