Nginx [Docker (installation of Nginx, Nginx service start and stop control, global block, events block, HTTP block)] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Docker install Nginx

Nginx service start and stop control

 Detailed explanation of Nginx configuration instructions_global block

Nginx configuration instructions detailed _events block

 Detailed explanation of Nginx configuration instructions_HTTP block


Docker install Nginx

 Pull the official Nginx image

[root@localhost ~]# docker pull nginx

The following command starts an Nginx container instance using the default Nginx configuration:

[root@localhost ~]# docker run --rm --name nginx-test -p 8080:80 -d nginx
358354f206fdbc5c20199a307392c11972b1bedab306144e5af56995edbb3e4b

The meaning of the parameters is as follows:

--rm: After the container terminates, automatically delete the container file

--name nginx-test: The name of the container is Nginx-test, and the name is defined by itself

-p: port mapping, mapping the local port 8080 to port 80 inside the container

-d: run in the background after the container starts

 Nginx service deployment, mapping local directory to Nginx container

Create a local directory for storing related file information of Nginx.

mkdir -p /opt/nginx/www /opt/nginx/conf

parameter:

The www: directory will be mapped as a virtual directory configured by the nginx container.

conf: The configuration files in the directory will be mapped to the configuration files of the nginx container.

 Copy the Nginx default configuration file in the container to the conf directory under the local current directory. The container ID can be viewed in the first column in the input of the docker ps command

docker cp 358354f206fd:/etc/nginx/nginx.conf /home/nginx/conf/

deployment command

docker run --rm -d -p 8081:80 --name nginx-test-web \
 -v /opt/nginx/www:/usr/share/nginx/html \
 -v
/opt/nginx/conf/nginx.conf:/etc/nginx/nginx.c
onf \
 nginx

Command description:

--rm: After the container terminates, automatically delete the container file.

-p 8081:80: Map port 80 of the container to port 8082 of the host.

--name nginx-test-web: Name the container Nginx-test-web -v /home/Nginx/www:/usr/share/Nginx/html: Mount the www directory we created to /usr of the container /share/Nginx/html.

-v /home/nginx/conf/nginx.conf:/etc/nginx/nginx.conf: Mount the nginx.conf we created to /etc/nginx/nginx.conf of the container.

 Real-time effect feedback

1. Docker installs Nginx and how to copy the nginx.conf file in the container to the local machine.

A docker -d

B docker --rm

C docker --name

D docker -cp

Nginx service start and stop control

Starting the Nginx service

On the Linux platform, start the Nginx server and directly run the binary files in the sbin directory under the installation directory.

 ./Nginx -h

parameter:

-v : print version number

-V : print version number and configuration

-t: test configuration correctness and exit

-q: only show errors when testing configuration

-s: send a signal to the main process

-p: Specify the Nginx server path prefix

-c: Specify the Nginx configuration file path

-g: Specify the Nginx additional configuration file path

Stopping the Nginx service 

Two ways:

Quick stop, quick stop means to immediately stop all network requests being processed by the current Nginx service, drop the connection immediately, and stop working.

 Nginx -s stop # Quick shutdown

 Graceful stop, gentle stop refers to allowing the Nginx service to complete the processing of the network request currently being processed, but no longer receive new requests, and then close the connection and stop working.

 Nginx -s quit # Wait for the worker process to finish processing and close

 NOTE: A gentle stop is recommended.

 Restart of Nginx service

After changing the configuration of the Nginx server and adding a new module, if you want the current Nginx service to apply the new configuration or make the new module take effect, you need to restart the Nginx service. Of course, we can shut down the Nginx service first, and then restart the service using the new Nginx configuration file.

Nginx -s reload # 向主进程发送信号,重新加载配置文件,热重启
Nginx -s reopen # 重启 Nginx

Real-time effect feedback

1. How to stop Nginx service smoothly.

A Nginx -s stop

B Nginx -s quit

C kill -9

D Nginx stop

2. How to hot restart Nginx service.

A ps aux|grep Nginx

B Nginx -s restart

C Nginx -s reopen

D Nginx -s reload

 Detailed explanation of Nginx configuration instructions_global block

 Configure the running Nginx server user (group)

The directive for configuring the user (group) running the Nginx server is user.

Grammar format:

user user [group]

 If you want all users to be able to start the Nginx process, there are two ways: one is to comment the following command:

# user [user] [group]

 Or set the user (and user group) to nobody;

user nobody nobody;

Configure the number of worker processes allowed to be generated 

The worker process is the key to the concurrent processing of the Nginx server. In theory, the larger the value of worker_process, the more concurrent processing it can support.

Grammar format: 

worker_process number | auto

number specifies the maximum number of worker_processes that the Nginx process can generate.

auto , set this value, the Nginx process will be detected automatically.

In the default configuration file, Number=1. After starting the Nginx server, use the following command to see that in addition to the main process master process ../sbin/Nginx, the Nginx server also generates a worker_process. 

ps aux|grep Nginx 

Note: Secondary commands can only be set in the global block. 

 Configure the Nginx process PID storage path

The Nginx process runs as a system daemon process, and we need to save the main process number of the currently running program in a file.

Grammar format: 

pid file;

Notice:

Sub-commands can only be set in the global block. When specifying the path, be sure to include the file name. If only the path is set but not the file name, an error will be reported.

Configure the storage path of error logs

 The logs of the Nginx server can be configured in the global block, http block and server block. Here we first introduce the log storage configuration under the global block. The configurations of the latter two cases are basically the same, but the scope is different.

Grammatical structures:

error_log_file | stderr[ debug|info | notice| warn |error|crit|alert]

Notice:

The specified file has write permission for the user running the Nginx process, otherwise the following error message will appear when starting the Nginx process:

Nginx:[alert] :could not open error log
file :open() "/Nginx/logs/error.log failed
(permission denied)"

Introduction of configuration files

In some cases, we may need to refer other Nginx configurations or configurations of third-party modules to the current main configuration file. Nginx provides include directives to complete the introduction of configuration files

Grammatical structures: 

include file;

Among them, file is the configuration file to be imported, which supports relative paths.

Notice:

The newly referenced files also require the user running the Nginx process to have write permission and conform to the relevant syntax and structure specified in the Nginx configuration file. This directive can be placed anywhere in the configuration file.

Real-time effect feedback

1. The role of the worker_process directive in the Nginx configuration file is.

A Speed ​​up Nginx startup speed

B Improve server concurrency

C Reduce server concurrency

D speed up worker startup 

2. Nginx configuration file directives are divided into several blocks.

A 1

B 2

C 3

D 4

Nginx configuration instructions detailed _events block

event-driven model 

The Nginx server provides a variety of event-driven models to process network messages. The configuration file provides us with relevant instructions to force the Nginx server to choose which event-driven model to process messages.

Grammatical structures:

use method;

Among them, the optional contents of method are: select, poll, kqueue, epoll, rtsig, ldev/poll l and eventport.

A) Standard event model

Select and poll belong to the standard event model. If there is no more effective method in the current system, Nginx will choose select or poll 

B) Efficient event model

  • Kqueue: used on FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 and MacOS X. Using kqueue on a dual-processor MacOS X system may cause a kernel panic.
  • Epoll: used in Linux kernel version 2.6 and later systems.
  • /dev/poll: for Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ and Tru64 UNIX 5.1A+.
  • Eventport: for Solaris 10. In order to prevent kernel panic problems, it is necessary to install security patches.

Note: You can use --with-select module and --without-select_module to set whether to force compile the select module to the Nginx kernel; use --with-poll_module and --without-poll_module to set whether to force compile the poll module to the Nginx kernel . This directive can only be configured in the events block. 

Configure the maximum number of connections 

The instruction worker_connections is mainly used to set the maximum number of connections that each worker process is allowed to open at the same time. Its grammatical structure is:

worker_connections number;

The default setting for this directive is 512.

Notice:

The maximum number of connections per worker process. Adjust according to the hardware, use it in conjunction with the previous work process, try to be as large as possible, but don't run the CPU to 100%. The maximum number of connections allowed by each process, theoretically the maximum number of connections per Nginx server is . worker_processes * worker_connections

Real-time effect feedback

1. The efficient event-driven model in the Nginx configuration file is.

A Select

B poll

C epoll

D socket 

 Detailed explanation of Nginx configuration instructions_HTTP block

Define MIME-Type

 Commonly used browsers can display a wide variety of text and media resources such as HTML, XML, GIF, and Flash. To distinguish these resources, browsers need to use MIME Type. In other words, MIME Type is the media type of a web resource. As a web server, the Nginx server must be able to identify the resource type requested by the front end.

include       mime.types;
default_type application/octet-stream;

 Look at the mime.types snippet:

Custom Service Log 

Record the log of the Nginx server providing the service process and answering the front-end request. We call it the service log to distinguish it. The Nginx server supports the configuration of the format, size, and output of the service log. Two instructions are required, namely the access_log and log_format instructions.

The syntax structure of the access_log command is:

access_log path[format[buffer=size]]

1. path, the path and name of the file where the configuration service log is stored.

2. format, optional, customizes the format string of the service log, and can also make the format defined by the log_format command through the "name of the format string". The "name of the format string" is defined in the log_format directive.

3. size, configure the size of the memory buffer for temporarily storing logs.

Another command used in conjunction with access_log is log_format, which is specifically used to define the format of the service log, and a name can be defined for the format string so that the access_log command can be called directly. Its syntax format is: 

log_format name string ..;

name, the name of the format string, the default name is combined.

string, the format string of the service log. During the definition process, you can use some variables preset by Nginx to obtain relevant content. The variable name is enclosed in double quotation marks, and the string as a whole is enclosed in single quotation marks. For the variables that can be used in string, please refer to the relevant content in "Appendix A" of this book.

log_format main '$remote_addr - $remote_user
[$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format log404 '$status [$time_local]
$remote_addr $host$request_uri
$sent_http_location';

 

日志格式设置 :
$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;

$remote_user:用来记录客户端用户名称;

$time_local: 用来记录访问时间与时区;

$request: 用来记录请求的url与http协议;

$status: 用来记录请求状态;成功是200,

$body_bytes_sent :记录发送给客户端文件主体内容大小;

$http_referer:用来记录从那个页面链接访问过来的;

$http_user_agent:记录客户浏览器的相关信息;

通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以
增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。

Configure connection timeout

After establishing a session connection with the user, the Nginx server can keep these connections open for a period of time, and the command keepalive_timeout is used to set this time.

Grammatical structures:

keepalive_timeout timeout [header timeout];
timeout,服务器端对连接的保持时间。默认值为75s。

header_timeout,可选项,在应答报文头部的Keep-Alive域设置超时时间"Keep-Alive:timeout= header_timeout”。报文中的这个指令可以被Mozilla或者Konqueror识别。

Configuration example:

keepalive_timeout 120s 100s;

It means that the time to keep the connection on the server side is set to 120 s, and the timeout time of the Keep-Alive field in the header of the response message sent to the client is set to 100 s.

Configure virtual host 

server{} is included inside http{}, each server{} is a virtual host (site)

Grammatical structures:

server{
}

Configure network monitoring

The command listen is used to configure monitoring, and there are two main configuration methods.

The first configuration monitors the IP address, the syntax structure is:

listen address[:port]

The second configuration listening port, the syntax structure is:

listen port

Parameters: address, IP address, if it is an IPv6 address, it needs to be enclosed in square brackets "[", such as [fe80::1], etc. port, the port number, if only the IP address is defined but not the port number, port 80 will be used.

example

listen 192.168.1.10:8000; #监听具体的IP和具体的端口上的连接

listen 192.168.1.10;     #监听具体IP的所有端口上的连接(没用)

listen 8000;             #监听具体端口上的所有IP连接

 Name-based virtual host configuration

The "host" here refers to the virtual host provided by this server block. After setting the name of the host and configuring DNS, users can use this name to send requests to this virtual host.

 grammar:

server_name name1 name2 name3 ...;

Example 1:

server_name www.baidu.com       //精确匹配

Example 2:

server_name   *.baidu.com;           //通配

Example 3:

server_name www.baidu.com *baidu.com;

four ways of writing

server_name www.baidu.com;
server_name *.baidu.com;
server_name www.baidu.*;
server_name   ~^www\.baidu\.*$;

priority

#运行用户
user nobody;
#启动进程,通常设置成和cpu的数量相等
worker_processes 1;
#全局错误日志及PID文件
#error_log logs/error.log;
#error_log logs/error.log notice;

#error_log logs/error.log info;
#pid       logs/Nginx.pid;
#工作模式及连接数上限
events {
   #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
   #仅用于linux2.6以上内核,可以大大提高Nginx的性能
   use   epoll;
   #单个worker进程的最大并发链接数    
   worker_connections 1024;
   # 并发总数是 worker_processes 和worker_connections 的乘积
   # 即 max_clients = worker_processes *worker_connections
   # 在设置了反向代理的情况下,max_clients =worker_processes * worker_connections / 4 为什么
   # 为什么上面反向代理要除以4,应该说是一个经验值
   # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
   # worker_connections 值的设置跟物理内存大小有关
   # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
   # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
# 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
   # $ cat /proc/sys/fs/file-max
   # 输出 34336
   # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
   # 所以,worker_connections 的值需根据worker_processes 进程数目和系统可以打开的最大文件
总数进行适当地进行设置
   # 使得并发总数小于操作系统可以打开的最大文件数目
   # 其实质也就是根据主机的物理CPU和内存进行配置
   # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
   # ulimit -SHn 65535
}

http {
   #设定mime类型,类型由mime.type文件定义
   include   mime.types;
   default_type application/octet-stream;
   #设定日志格式
   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 logs/access.log main;

#sendfile 指令指定 Nginx 是否调用 sendfile函数(zero copy 方式)来输出文件,
   #对于普通应用,必须设为 on,
   #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
   #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
   sendfile     on;
   #tcp_nopush     on;
   #连接超时时间
   #keepalive_timeout 0;
   keepalive_timeout 65;
   tcp_nodelay     on;
   #开启gzip压缩
   gzip on;
   gzip_disable "MSIE [1-6].";
   #设定请求缓冲
   client_header_buffer_size   128k;
   large_client_header_buffers 4 128k;
   #设定虚拟主机配置
   server {
       #侦听80端口
       listen   80;
       #定义使用 www.Nginx.cn访问
       server_name www.Nginx.cn;
       #定义服务器的默认网站根目录位置(编译的时候--prefix是整个Nginx的根目录,这里的html文件夹是相对--prefix的路径)
       root html;
       #设定本虚拟主机的访问日志
       access_log logs/Nginx.access.log main;
       #默认请求
       location / {
            
           #定义首页索引文件的名称
           index index.php index.html  index.htm;  
       }
       # 定义错误提示页面
       error_page   500 502 503 504 /50x.html;
       location = /50x.html {
       }
       #静态文件,Nginx自己处理
       location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
           #过期30天,静态文件不怎么更新,过期可以设大一点,
           #如果频繁更新,则可以设置得小一点。
           expires 30d;
       }
       #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
       location ~ .php$ {
           fastcgi_pass 127.0.0.1:9000;
           fastcgi_index index.php;
           fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
           include fastcgi_params;
       }
       #禁止访问 .htxxx 文件
           location ~ /.ht {
           deny all;
       }
   }
}

 Real-time effect feedback

1. In the Nginx core configuration file, the virtual host configuration order is ____ based on the name.

A Exact match, right wildcard, left wildcard, regular expression

B Regular expression, left wildcard, right wildcard, exact match

C exact match, left wildcard, right wildcard, regular expression

D Exact match, regular expression, wildcard on the right, wildcard on the left

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131494920