1. Nginx process model
Nginx is a master-worker process model.
The Master process: The main process that monitors the worker process.
Worker processes: Work process, do the corresponding work.
The number of worker processes can be configured through the configuration file. The default value is 1, as shown in the following figure.
The following figure shows the workflow diagram of Master and Worker processes.
2. How the Worker process works
2.1 Worker process preemption mechanism
As shown in the figure below, if we have three worker processes configured in the configuration file, matser will fork out three worker processes when nginx is started. If the client initiates a request, the three work processes will compete for the lock (accept_mutex lock), and whoever grabs the lock will get the lock.
2.2 Asynchronous non-blocking feature
Nginx is asynchronous and non-blocking
Under Linux, Nginx uses epoll’s I/O multiplexing model, and each worker can process multiple client requests simultaneously
Default conf file
Events {# epoll use epoll; Worker_connections 1024; }Copy the code
3. Nginx. conf configuration details
3.1 Configuration structure of nginx.conf
3.2 Nginx. conf core configuration
- Setting the user of the worker process (Linux user) involves some permissions of nginx to operate directories or files. The default is nobody.
If the value is root, go to the sbin directory under nginx ./nginx -s reload
Command to restart the system. The following worker user changes from nobody to root.
2. Set the number of CPU cores that the worker processes work on, or set it to n-1.
3. Nginx log level debug | info | notice | warn | error | crit | alert | emerg, error level from left to right is more and more big
4. Set the PID of the nginx process
The paths above 3 and 4 were specified when we installed Nginx.Juejin. Cn/post / 690453…
- Setting working Mode
Events {# epoll use epoll; # Worker_connections 10240; # worker_connections 10240; }Copy the code
- HTTP is a block of instructions, which are configured for HTTP network transmission
http {
}
Copy the code
- Include introduces foreign configurations to improve readability and prevent a single configuration file from being too large
include mime.types;
Copy the code
- Access_log specifies the path to the log file when you install nginx. Here, you use the default configuration of nginx.
9. Sendfile uses efficient file transfer to improve transmission performance. Tcp_nopush can be used only after it is enabled. It means that the data table is sent after it has accumulated a certain size, which improves efficiency.
- Keepalive_timeout Specifies the timeout period for requests from the client and the server to ensure that the connection is not set up repeatedly when the client requests the request for multiple times, saving resource consumption (unit: s).
-
Gzip on Enables the compression of HTML, CSS, and JS files to reduce the size and improve the transmission efficiency. However, it consumes server performance.
-
Server module – Virtual host, multiple can be configured
Supplement:
Go to the sbin directory and run the following command ./nginx -t
You can check whether the configuration file is correct.
Conclusion figure:
4. Nginx. pid failed to open and invalid solution
1. Failed to open 2. Invalid PID
5. Introduction to common Nginx commands
Nginx-s quit elegant stop nginx, when there is connection, wait for the connection request to complete before killing the worker process nginx-s reload elegant restart, reload the configuration file nginx.conf nginx-s reopen and reopen the log file, Nginx -v Displays the detailed version information about nginx -v, including the compilation parameter. Nginx -t Checks the nginx configuration file. Nginx -h Displays the help informationCopy the code
6. Nginx log cutting
6.1 Manually Cutting Logs
Existing log is the/var/log/nginx/directory, which is specified when we install the corresponding position, including two log/var/log/nginx/error log and/var/log/nginx/access. The log, but as time goes on, Log file will be more and more, the volume will be more and more big, the operations staff to check, so we can put the big log cutting into multiple small files as a log, cutting rules can be on a if there are hundreds of G every day or a few T file, it can be cut in half a day or hour. The procedure is as follows: 1. Create a shell executable file cut_my_log.sh and its contents are as follows: Note that the following scripts are cut by minutes. RECORD_TIME=$(date -d “yesterday” +%Y-%m-%d).
#! /bin/bash
LOG_PATH="/var/log/nginx"
RECORD_TIME=$(date -d "yesterday" +%Y-%m-%d+%H:%M)
PID=/var/run/nginx/nginx.pid
mv ${LOG_PATH}/access.log ${LOG_PATH}/access.${RECORD_TIME}.log
mv ${LOG_PATH}/error.log ${LOG_PATH}/error.${RECORD_TIME}.log
#Sends a signal to the main Nginx process to restart logging
kill -USR1 `cat $PID`
Copy the code
2. Add executable permission for cut_my_log.sh
chmod +x cut_my_log.sh
Copy the code
3. Test the result of log cutting
./cut_my_log.sh
Copy the code
6.2 Cutting Periodic Logs
1. Install scheduled tasks
yum install crontabs
Copy the code
Crontab -e edit and add a new task
*/1 * * * * /usr/local/nginx/sbin/cut_my_log.sh
Copy the code
3. Restart the scheduled task
service crond restart
Copy the code
conclusion:
7. Use Nginx as static resource server
7.1 HTML,CSS,JS routing
You can also use the include command to import a new configuration. For example, you can create a new imooc.conf and import the plug-in conf configuration to nginx.conf.
The nginx.conf configuration is as follows:
The imooc.conf configuration is as follows:
If we access the/directory, we will be routed to the /home/foodie-shop/ directory. The home page is index.html. If we access the server IP: port 90, we will be routed to the /home/foodie-shop/ directory. It will be routed to index.html under the foodie-shop project.
7.2 Image and audio routes
For other non-HTML, JS, CSS and other resources, can also be deployed on Nginx, here we do the following demonstration. We still use port 90 as the route, and add a location in the same server, but it should be noted that this location can no longer be /, because it will repeat the above location /, and we will put the images, audio and video resources in the /home/imooc folder. When configuring location, we do the following configuration.
At this point, /imooc will automatically concatenate /home to get the correct path. Browser access IP +90+/ iMOOc /+ resource name access.
Of course we can go further and use aliases. As follows:
If you call /static here, you’re going to look for resources under /home/imooc.
7.3 Introduction to the Matching Rules of Location
1. Space: default match, normal match
location / {
root /home;
}
Copy the code
2. = : Accurate matching
location = /imooc/img/face1.png {
root /home;
}
Copy the code
3. ~* : matches the regular expression and is case insensitive
# conform to the picture shows the location ~ * \. (GIF | JPG | PNG | jpeg) {root/home; }Copy the code
4. ~ : matches regular expressions and is case sensitive
# GIF must be in upper case. If you access the static resource in /home, you can route it to the corresponding file. For example, there is a static folder in the home directory where images are stored. Then access IP port/static / + 1. JPG can access to the location ~ \. (GIF | JPG | PNG | jpeg) {root/home; }Copy the code
5. ^~ : starts with a character path
Location ^~ /imooc/img {root /home; }Copy the code
8. Use Gzip compression to improve request efficiency
# Enable gZIP compression to improve transmission efficiency and save bandwidth. Gzip_min_length 1; # Define the level of compression (compression ratio, the larger the file, the more compression, but the more CPU usage) Gzip_types text/plain application/javascript application/x-javascript text/ CSS application/ XML text/javascript application/x-httpd-php image/jpeg image/gif image/png applicatio n/json;Copy the code
9. Nginx cross-domain configuration
Note: Both the nGINx cross-domain configuration and the previous SpringBoot cross-domain configuration can solve the cross-domain problem with just one configuration. Juejin. Cn/post / 688292…
Cross-domain configuration:
Add_header 'access-control-allow-origin' *; Add_header 'access-control-allow-credentials' 'true'; GET/POST/PUT/DELETE add_header 'access-control-allow-headers' *; Add_header 'access-control-allow-methods' *;Copy the code
The detailed configuration is as follows:
Worker_processes 1 can be adjusted to increase the number of cpus; Events {# worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; # Connection timeout, after which the server will close the connection. keepalive_timeout 10; # gizp compress gzip on; This is not required if the proxy address is already allowed to cross domains, otherwise the error will be reported (although this makes nginx cross domains invalid) Add_header 'access-control-allow-origin' *; Add_header 'access-control-allow-credentials' 'true'; GET/POST/PUT/DELETE add_header 'access-control-allow-headers' *; Add_header 'access-control-allow-methods' *; The srever module is a submodule of the HTTP module that defines a virtual access host server {listen 80; server_name localhost; / {root HTML; index index.html index.htm; } # Redirection error page to /50x.html error_page 500 502 503 504/50x.html; location = /50x.html { root html; }}}Copy the code
10. Configure static resource anti-link theft in Nginx
Prevent other sites after cross-domain purloin image links. Add the following configuration to the nginx.conf file.
# Valid_referers *.chen.com; If ($invalid_referer) {return 404; }Copy the code
11. Nginx is the reverse proxy
The following is an example:
Upstream Tomcats {server 123.89.195.81:8080; Server 123.89.195.82:8080; Server 123.89.195.83:8080; } server { listen 80; Server_name 123.89.195.79; location / { proxy_pass http://tomcats; }}Copy the code
In this case, the IP address + port 80 of nginx will be routed to the next three Tomcat servers.
12. Nginx load balancing policy
- Polling (default)
Web requests from clients are distributed to different back-end servers in sequence according to the order in the Nginx configuration file.
Upstream server_group {server backend1.example.com; server backend2.example.com; }Copy the code
- The weight
upstream server_group { server backend1.example.com weight=5; # Default is not to configure the weight to 1 server backend2.example.com; }Copy the code
- ip_hash
hash(ip)%node_counts = index
Copy the code
Ip_hash ensures that a user can access a fixed server in the upstream service, provided that the user IP address has not changed. Note when using ip_hash: the background server cannot be removed directly, only marked down.
upstream tomcats {
ip_hash;
server 192.168.1.173:8080;
server 192.168.1.174:8080 down;
server 192.168.1.175:8080;
}
Copy the code
- url_hash
According to the URL address of each request, hash and access to a fixed server node.
upstream tomcats {
# url hash
hash $request_uri;
server 192.168.1.173:8080;
server 192.168.1.174:8080;
server 192.168.1.175:8080;
}
server {
listen 80;
server_name www.tomcats.com;
location / {
proxy_pass http://tomcats;
}
Copy the code
- least_conn
Minimum number of connection requests, the request will be allocated to the server with the minimum number of connections.
Upstream tomcats {# minimum connection number least_conn server 192.168.1.173:8080; Server 192.168.1.174:8080; Server 192.168.1.175:8080; } server { listen 80; server_name www.tomcats.com; location / { proxy_pass http://tomcats; }Copy the code
13. Upstream parameter record
- Max_conns Maximum number of connections on the node
Upstream tomcats {server 192.168.1.173:8080 max_conns=2; }Copy the code
- Slow_start Indicates the slow start time. This parameter cannot be used for hash and Random Load balancing. If there is only one server in the upstream, this parameter is invalid.
Upstream tomcats {server 192.168.1.173:8080 weight=6 slow_start=60s; Server 192.168.1.174:8080 weight = 2; Server 192.168.1.175:8080 weight = 2; }Copy the code
- The Down node goes offline, indicating that the current server does not participate in load temporarily and the server node is unavailable
Upstream tomcats {server 192.168.1.173:8080 down; Server 192.168.1.174:8080 weight = 1; Server 192.168.1.175:8080 weight = 1; }Copy the code
- Backup Indicates the standby node. It will be added to the cluster only after other servers are down. The backup parameter cannot be used in hash and Random Load balancing.
Upstream tomcats {server 192.168.1.173:8080 backup; Server 192.168.1.174:8080 weight = 1; Server 192.168.1.175:8080 weight = 1; }Copy the code
- Max_fails Specifies the maximum number of allowed failures
- Fail_timeout Waiting time after the number of failures exceeds the maximum
max_fails=2 fail_timeout=15s
Copy the code
It means that if the request for a certain server fails twice within 15 seconds, the server is considered to have been suspended or down. Then, after 15 seconds, there will be no new request to the node that has just been suspended, but will be called to the operating server. After 15 seconds, there will be another new request to try to connect to the suspended server. If it still fails, repeat the previous process until it recovers.
14. Use the Keepalive configuration to improve performance
Proxy_http_version: sets the HTTP version of the long connection to 1.1. Proxy_set_header: clears connection header information
Upstream Tomcats {server 192.168.1.190:8080; keepalive 32; } server { listen 80; server_name www.tomcats.com; location / { proxy_pass http://tomcats; Proxy_http_version 1.1; proxy_set_header Connection ""; }Copy the code
Case of 15.
It is recorded here that nGINX is deployed on an Ali Cloud server. Static resources and background code are deployed on this server, and the background code is deployed on Tomcat.
Upstream tomcats {server 121.**.195.81:8088; } server { listen 81; server_name yun.j*-**-***.cn; location / { proxy_pass http://tomcats; }}Copy the code
server { listen 81; server_name shop.j*-**-***.cn; , location / {root /home/ foodie-shop; index index.html; } } server { listen 81; server_name center.j*-**-***.cn; location / { root /home/website/foodie-center; index index.html; }}Copy the code
A server corresponding to the three different level 3 domain names, this port is set to 81, because the domain name has not put on record, the default port 80, can be accessed at this time, we visit a different domain name will play to a different service, nginx tomcat deployed here in the background of interface service implements the reverse proxy, and implement the action.