Centos7 source code compilation, installation and tuning of nginx 1.19, adding new modules to the installed nginx

Philosophy of life 2020-11-10 17:23:34
centos7 centos source code compilation


One . About nginx

​ nginx By 1994 He graduated from Bauman University of science and technology in Moscow, Russia rambler.ru company-developed , Development started with 2002 Year begins , for the first time

The time for public release is 2004 year 10 month 4 Japan , The version number is 0.1.0

Nginx It's a single process, single thread model , In other words, only one process is started to respond to client requests , Unlike apache You can start multiple threads within a process to respond to requests ,

So in terms of memory usage, it's better than apache Many small .Nginx Maintain 10000 inactive conversations as long as 2.5M Memory .Nginx and MySQL yes CPU intensive , That's right CPU The occupancy ratio of

more , Default session Save in local files , Support will session Save in memcache, however memcache The default support is maximum 1M Of hash object .

nginx The version of is divided into development version 、 Stable and expired ,nginx It's famous for its rich functions , It can be used as http The server , It can also be used as a reverse proxy server or mail

The server , Be able to quickly respond to static web page requests , Support FastCGI/SSL/Virtual Host/URL Rwrite/Gzip/HTTP Basic Auth And so on , And support third parties

Function extension .

Two .nginx Installation method of

​ nginx Installation can use yum Or source installation , Recommended source code , One is yum The version of is older , Second, the use of source code can be customized function , Convenient for business use .

​ Source code installation requires the preparation of a standard compiler in advance ,GCC The full name is (GNU Compiler collection), The reason is GNU Development , And GPL namely LGPL The license , It's free

class UNIX Apple computer Mac OS X Standard compiler for operating systems , because GCC Could only deal with C Language , So it was originally called GNU C Language compiler , Later I got a quick hair

exhibition , Can handle C++,Fortran,pascal,objective-C,Java as well as Ada Other languages , In addition, we need Automake Tools , To complete the automatic creation of Makefile Work of

do ,Nginx Some of the modules need to rely on third-party libraries , such as pcre( Support rewrite),zlib( Support gzip modular ) and openssl( Support ssl modular ).

3、 ... and . Source code compilation and installation nginx

3.1 download nginx Source code and decompress

[root@node5 ~]# wget http://nginx.org/download/nginx-1.19.3.tar.gz
[root@node5 ~]# ls nginx-1.19.3.tar.gz -lh
-rw-r--r-- 1 root root 1.1M Sep 29 22:39 nginx-1.19.3.tar.gz
[root@node5 ~]# tar xf nginx-1.19.3.tar.gz
[root@node5 ~]# cd nginx-1.19.3
[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src

3.2 establish nginx Users and groups

[root@node5 nginx]# groupadd nginx
[root@node5 nginx]# useradd -g nginx nginx
[root@node5 nginx]# id nginx
uid=8000(nginx) gid=8000(nginx) groups=8000(nginx)
[root@node5 nginx]# grep nginx /etc/passwd
nginx:x:8000:8000::/home/nginx:/bin/bash
# Set up linux High load parameters , Adjust file descriptors
[root@node5 nginx]# ulimit -SHn 65535

3.3 install nginx Compile environment ( Solve the problem of dependence )

nginx The components needed for compiling are introduced :

​ gcc by GNU Compiler Collection Abbreviation , You can compile C and C++ Source code, etc , It is GNU Developed C and C++ And many other languages The compiler ( One of the earliest

You can only compile C, And then it quickly evolved into a collection of multiple languages , Such as Fortran、Pascal、Objective-C、Java、Ada、 Go etc. .)

​ gcc Compiling C++ Source code phase , Only compile C++ Source file , And not automatically and C++ Library links used by the program ( The compilation process is divided into compilation 、 Link two stages , Be careful

Don't get confused with the concept of executable files , There are three important concepts relative to executable files : compile (compile)、 link (link)、 load (load). Source code text

Files are compiled into object files , Multiple target files and libraries are linked to form a final executable file , The executable file is loaded into memory to run ). therefore , Usually use g++ life

Order to complete C++ Program compilation and linking , The program will automatically call gcc Implement compilation .

​ gcc-c++ Can also compile C Source code , Just think of it as C++ Source code , The suffix is .c Of ,gcc Think of it as C Program , and g++ As if c++ Program ; The suffix is .cpp

Of , Both of them will think that c++ Program , Be careful , although c++ yes c Superset , But there is a difference between the two .

​ automake It is a slave. Makefile.am Automatic file generation Makefile.in Tools for . In order to generate Makefile.in,automake There is also a need for perl, because automake gen

Build's release follows exactly GNU standard , So you don't need to perl.libtool Is a convenient tool to generate a variety of Libraries .

​ pcre pcre-devel: stay Nginx Compile time , need PCRE(Perl Compatible Regular Expression), because Nginx Of Rewrite Module and HTTP The core module will

Use to PCRE regular expression syntax .pcre-devel It's using pcre Development of a secondary development library .

​ zlip zlib-devel:zlib The library provides many ways to compress and decompress , nginx Use zlib Yes http The contents of the package go on gzip , So you need to be in Centos Installation on

zlib library .nginx When compression is enabled , Support for this module is required .

​ openssl openssl-devel:OpenSSL Is a strong secure socket layer password library , Including the main cipher algorithm 、 Common key and certificate encapsulation management functions and SSL

agreement , And provide rich applications for testing or other purposes .nginx Not only support http agreement , And support https( That is to say ssl Over protocol transmission http). Turn on SSL Of

When you need the support of this module .

[root@node5 ~]# yum -y install gcc gcc-c++ automake pcre pcre-devel zlip zlib-devel openssl openssl-devel
Loaded plugins: fastestmirror
......
Package 1:openssl-1.0.2k-19.el7.x86_64 already installed and latest version
Package 1:openssl-devel-1.0.2k-19.el7.x86_64 already installed and latest version
Nothing to do

3.4 Check the system environment

​ Check whether the system environment meets the requirements of compilation and installation , For example, whether there is gcc Compiler tools , Whether to support the modules in the compilation parameters , And generate according to the open parameters Makefile

File for the next step :

[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src
[root@node5 nginx-1.19.3]# ./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
checking for OS
+ Linux 3.10.0-693.el7.x86_64 x86_64
checking for C compiler ... found
......
nginx http uwsgi temporary files: "/var/tmp/nginx/uwsgi"
nginx http scgi temporary files: "/var/tmp/nginx/scgi"
#echo $? Output is 0, The last step is right
[root@node5 nginx-1.19.3]# echo $?
0

3.5 compile nginx

[root@node5 nginx-1.19.3]# make -j 4
[root@node5 nginx-1.19.3]# echo $?
0

3.6 Compilation and installation nginx

[root@node5 nginx-1.19.3]# make install
[root@node5 nginx-1.19.3]# echo $?
0

3.7 start-up nginx

[root@node5 nginx-1.19.3]# cd /usr/local/nginx/
[root@node5 nginx]# ls
conf html sbin
[root@node5 nginx]# pwd
/usr/local/nginx
# see nginx Detailed version information
[root@node5 nginx]# sbin/nginx -V
nginx version: nginx/1.19.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-te -path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi -▽with-pcre
# start-up nginx Report errors , Need to create /var/tmp/nginx/client/ Catalog
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)
[root@node5 nginx]# su nginx
[nginx@node5 nginx]$ mkdir -p /var/tmp/nginx/client/
[nginx@node5 nginx]$ exit
exit
# Start again nginx
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
# You can see nginx Successful launch
#master process yes nginx The main process of , There is only one main process
#worker process yes nginx Working process , There is only one default , It can be modified by nginx.conf Medium worker_processes 1; Parameter to start multiple worker processes
[root@node5 nginx]# ps -ef | grep nginx
root 14592 1 0 16:33 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 14593 14592 0 16:33 ? 00:00:00 nginx: worker process
root 14604 128012 0 16:33 pts/1 00:00:00 grep --color=auto nginx
# stop it nginx
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -s stop
[root@node5 nginx]# ps -ef | grep nginx
root 14765 128012 0 16:36 pts/1 00:00:00 grep --color=auto nginx

3.8 nginx Directory function introduction :

  • ​ conf: preservation nginx All configuration files , among nginx.conf yes nginx The most important configuration file of the server , Other .conf It is used to configure nginx Related to the function of , for example fastcgi The function uses fastcgi.conf and fastcgi_params Two documents , Configuration files usually have a template configuration file , File name .default ending , Make a copy when using , Get rid of default Suffixes are enough .
  • ​ html There is... In the catalogue nginx Server's web file , But you can change it to another directory to save web file , There's another one 50x Of web File is the default error page prompt page .
  • ​ logs: For preservation nginx Server access log , Error log, etc ,logs Directories can be placed in other paths , such as /var/logs/nginx Inside .
  • ​ sbin: preservation nginx Binary startup script , Different parameters can be accepted to achieve different functions .
[root@node5 ~]# cd /usr/local/nginx/
[root@node5 nginx]# pwd
/usr/local/nginx
[root@node5 nginx]# ls
conf html sbin
[root@node5 nginx]# ls conf/
fastcgi.conf fastcgi_params koi-utf mime.types nginx.conf scgi_params uwsgi_params win-utf
fastcgi.conf.default fastcgi_params.default koi-win mime.types.default nginx.conf.default scgi_params.default uwsgi_params.default
[root@node5 nginx]# ls html/
50x.html index.html
[root@node5 nginx]# ls sbin/
nginx
[root@node5 nginx]# ls /var/log/nginx
access.log error.log

Four . Set up nginx Boot up

​ Set up nginx Boot up , And use systemctl management , There are two ways to do this , Choose one of them

Method 1 :

# Create soft link
[root@node5 nginx]# ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
[root@node5 nginx]# ll /usr/bin/nginx
lrwxrwxrwx 1 root root 27 Oct 22 16:43 /usr/bin/nginx -> /usr/local/nginx/sbin/nginx
[root@node5 nginx]# vim /etc/init.d/nginx
#/etc/init.d/nginx Is as follows
[root@node5 ~]# cat /etc/init.d/nginx
#!/bin/bash
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: NGINX is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /usr/local/nginx/conf/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
#lockfile=/var/lock/subsys/nginx
lockfile=/var/lock/nginx.lock
make_dirs() {
# make required directories
user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
if [ -z "`grep $user /etc/passwd`" ]; then
useradd -M -s /bin/nologin $user
fi
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
[root@node5 ~]#
#/etc/init.d/nginx Give scripts executable rights
[root@node5 nginx]# chmod a+x /etc/init.d/nginx
[root@node5 nginx]# ll !$
ll /etc/init.d/nginx
-rwxr-xr-x 1 root root 2649 Oct 22 17:48 /etc/init.d/nginx
[root@node5 nginx]# chkconfig --add /etc/init.d/nginx
[root@node5 nginx]# chkconfig nginx on
# start-up nginx
[root@node5 nginx]# systemctl start nginx
# see nginx Start state
[root@node5 nginx]# ps -ef | grep nginx
root 18530 1 0 17:49 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 18531 18530 0 17:49 ? 00:00:00 nginx: worker process
root 18547 128012 0 17:50 pts/1 00:00:00 grep --color=auto nginx
# see nginx Start state
[root@node5 nginx]# systemctl status nginx
● nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
Active: active (running) since Thu 2020-10-22 17:49:55 CST; 1min 24s ago
Docs: man:systemd-sysv-generator(8)
Process: 18434 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
Main PID: 18530 (nginx)
CGroup: /system.slice/nginx.service
├─18530 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
└─18531 nginx: worker process
Oct 22 17:49:55 node5 systemd[1]: Starting SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:49:55 node5 nginx[18434]: Starting nginx: [ OK ]
Oct 22 17:49:55 node5 systemd[1]: Started SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.
# stop it nginx
[root@node5 nginx]# systemctl stop nginx
[root@node5 nginx]# systemctl status nginx
● nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
Active: inactive (dead) since Thu 2020-10-22 17:51:29 CST; 4s ago
Docs: man:systemd-sysv-generator(8)
Process: 18623 ExecStop=/etc/rc.d/init.d/nginx stop (code=exited, status=0/SUCCESS)
Process: 18434 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
Main PID: 18530 (code=exited, status=0/SUCCESS)
Oct 22 17:49:55 node5 systemd[1]: Starting SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:49:55 node5 nginx[18434]: Starting nginx: [ OK ]
Oct 22 17:49:55 node5 systemd[1]: Started SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.
Oct 22 17:51:29 node5 systemd[1]: Stopping SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:51:29 node5 nginx[18623]: Stopping nginx: [ OK ]
Oct 22 17:51:29 node5 systemd[1]: Stopped SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.
[root@node5 nginx]# ps -ef | grep nginx
root 18649 128012 0 17:51 pts/1 00:00:00 grep --color=auto nginx

Method 2 :

[root@node5 nginx]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/var/run/nginx/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP /var/run/nginx/nginx.pid
ExecStop=/bin/kill -s QUIT /var/run/nginx/nginx.pid
PrivateTmp=true
[Install]
WantedBy=multi-user.target
# Join boot and boot Nginx
[root@node5 nginx]# systemctl enable nginx.service
[root@node5 nginx]# systemctl restart nginx.service

5、 ... and . test nginx Whether the function is normal

# The following output can appear nginx Successful startup
[root@node5 nginx]# curl 192.168.110.184:80
<!DOCTYPE html>
<html>
<head>
......
<p><em>Thank you for using nginx.</em></p>
</body>
</html>

A little more intuitive, you can check the browser

image-20201022181503533

6、 ... and . Open the firewall 80 port

If the firewall is up , Need to set up Firewalld A firewall , hold 80 The port is open

# Start the firewall
[root@node5 nginx]# systemctl start firewalld
[root@node5 nginx]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: active (running) since Thu 2020-10-22 18:17:11 CST; 1s ago
Docs: man:firewalld(1)
Main PID: 20056 (firewalld)
CGroup: /system.slice/firewalld.service
└─20056 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
Oct 22 18:17:11 node5 systemd[1]: Starting firewalld - dynamic firewall daemon...
Oct 22 18:17:11 node5 systemd[1]: Started firewalld - dynamic firewall daemon.
Oct 22 18:17:11 node5 firewalld[20056]: WARNING: ICMP type 'beyond-scope' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: beyond-scope: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: ICMP type 'failed-policy' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: failed-policy: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: ICMP type 'reject-route' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: reject-route: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.
# hold 80 Port open
[root@node5 nginx]# firewall-cmd --zone=public --add-port=80/tcp --permanent
success
[root@node5 nginx]# firewall-cmd --reload
success
[root@node5 nginx]# curl 192.168.110.184:80

If you finish setting up the firewall , Browsers can also access nginx page , Indicates that the setting is successful .

7、 ... and .nginx Log cutting

Method 1 :

1.nginx Log files are not automatically cut by default , have access to shell Script with crontab Make automatic cutting log .

2. A command is used in the log cutting script :kill -USR1 nginx The main process number of . The function of this command is : towards nginx The main process sends USR1 The signal ,nginx The main process receives a signal

The log file name will be read from the configuration file , Reopen the log file ( Named after the log name in the configuration file ) , And as the owner of the user's process

After the new log file is opened ,nginx The main process will close the duplicate log file and notify the worker process to use the newly opened log file . The worker immediately opens the new log file and closes

Log files with duplicate names , Then you can deal with old log files .

3. Write log cutting script

# The script of the cutting log is as follows
[root@node5 ~]# cat nginx_log_rotate.sh
#!/bin/bash
# Script execution , Quit when you make a mistake , No further execution
set -e
# With timed tasks ,0 Click a second to start the cutting task
sleep 1
# Inquire about nginx Main process number
PID=`cat /var/run/nginx/nginx.pid`
# Get the server yesterday's time
yesterday=$(date -d 'yesterday' +%Y-%m-%d)
#nginx Log file directory of
ng_logs_dir='/var/log/nginx/'
# Judge nginx Whether the log directory exists , If it exists, it will cut the log
if [ -d $ng_logs_dir ];then
cd $ng_logs_dir
# adopt mv Command to move the log to the split log ,error Logs are generally not cut
mv access.log access_${yesterday}.log
# send out kill -USR1 Signal to Nginx The main process number of , Give Way Nginx Regenerate a new log file
kill -USR1 $PID
sleep 1
# Pack old logs into a compressed package
tar -czf access_${yesterday}.log.tar.gz access_${yesterday}.log
# Existing compressed package , Delete the log before compression
rm -f access_${yesterday}.log
else
echo "nginx The log directory does not exist , Please check "
exit 0
fi
# Give the script executable rights
[root@node5 ~]# chmod +x nginx_log_rotate.sh
[root@node5 ~]# ll nginx_log_rotate.sh
-rwxr-xr-x 1 root root 951 Oct 26 15:36 nginx_log_rotate.sh
[root@node5 ~]# ll -h /var/log/nginx/
-rw-r--r-- 1 nginx root 11K Oct 26 15:37 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log
# Run the script manually to see the effect
[root@node5 ~]# bash nginx_log_rotate.sh
[root@node5 ~]# ll -h /var/log/nginx/
-rw-r--r-- 1 root root 418 Oct 26 15:37 access_2020-10-25.log.tar.gz
-rw-r--r-- 1 nginx root 0 Oct 26 15:37 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log

4. Set up crontab Timing task , Execute scripts every morning

[root@node5 ~]# crontab -e
[root@node5 ~]# crontab -l
0 0 * * * bash /root/nginx_log_rotate.sh

Method 2 :

#nginx The log cutting script is as follows
[root@node5 ~]# cat logqiege.sh
#!/bin/bash
PID=`cat /var/run/nginx/nginx.pid`
mv /var/log/nginx/access.log /var/log/nginx/`date +%Y_%m_%d:%H:%M:%S`.access.log
kill -USR1 $PID
[root@node5 ~]# chmod +x logqiege.sh
[root@node5 ~]# ll -h /var/log/nginx/
total 20K
-rw-r--r-- 1 nginx root 14K Oct 26 15:58 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log
[root@node5 ~]# bash logqiege.sh
[root@node5 ~]# ll -h /var/log/nginx/
total 20K
-rw-r--r-- 1 nginx root 14K Oct 26 15:58 2020_10_26:15:58:38.access.log
-rw-r--r-- 1 nginx root 0 Oct 26 15:58 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log
[root@node5 ~]# crontab -e
[root@node5 ~]# crontab -l
*/1 * * * * bash /root/logqiege.sh

Method 3 :

1. Advanced usage – Use nginx By itself
When nginx In a container , hold nginx When the log is mounted , We found that it was not suitable for reuse kill -USR1 The way to split the log , Of course, from now on nginx

The configuration solves this problem , We all know that there is a time related field in the access log , If we take this time out , This problem is solved

Let's look at generating access logs by day

 if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
}
access_log /var/log/nginx/${year}_${month}_${day}_access.log json;
# Or scripts can be written like this
# Cutting log
if ($time_iso8601 ~ '(\d{4}-\d{2}-\d{2})') {
set $tttt $1;
}
access_log /home/wwwlogs/access-$tttt.log ;

View the results of the log generation

image-20201026163320375

2. See the log has been cut out according to our needs , This log cutting can reach the second level , The usage is the same , Just get rid of the regular match to the timestamp .nginx built-in

There are many variables of , Columns such as ${server_name} These variables can be used to name the log , Of course, if we need compression , Write a corresponding timing task to do compression .

8、 ... and . to nginx The main process sends a signal to nginx The stop of , upgrade , Log cutting

1. obtain nginx Main process number method :

# obtain nginx Main process number method : Method 1
[root@node5 ~]# ps -ef | grep nginx
root 19806 1 0 Oct23 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 19807 19806 0 Oct23 ? 00:00:00 nginx: worker process
root 97457 77960 0 17:01 pts/7 00:00:00 grep --color=auto nginx
# obtain nginx Main process number method : Method 2 :
# see nginx Of pid file , What this file holds is nginx The main process of id, this ID Is random , Every time it starts, it's different
[root@node5 ~]# cat /var/run/nginx/nginx.pid
19806

2.nginx The supporting signals are as follows

#nginx Supported signals :
# Close smoothly Nginx, That is, no new requests will be accepted , But wait until the current request has been processed Nginx.
[root@node5 ~]# kill -QUIT 19806
# Stop quickly Nginx service
[root@node5 ~]# kill -TERM 19806
# Start the process with the new configuration file, and then gently stop the original nginx process , Smooth restart .
[root@node5 ~]# kill -HUP 19806
# Re open the configuration file , be used for nginx Log cutting , For specific log cutting techniques, please check “nginx Log cutting ” chapter
[root@node5 ~]# kill -USR1 19806
# Use the new version of nginx File start service , And then gently stop the original nginx service , Smooth upgrade .
[root@node5 ~]# kill -USR2 21703
# Smooth stop nginx Working process of , be used for nginx Smooth upgrade .
[root@node5 ~]# kill -WINCH 21703
#Nginx,-s Adopt the direction of Nginx How to send a signal ,-s signal:send signal to a master process: stop, quit, reopen, reload
# The way to stop the step is to wait for nginx Process processing task completed to stop .
[root@node5 ~]# nginx -s quit
# This is equivalent to finding out nginx process id Reuse kill Order to force the killing process .
[root@node5 ~]# nginx -s stop

Nine .nginx Common commands

Here is a list of nginx Frequently used commands

# see Nginx Version number of
[root@node5 ~]# /usr/local/nginx/sbin/nginx -v
nginx version: nginx/1.19.3
# see Nginx Version number and compilation parameters of
[root@node5 ~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
# start-up nginx:nginx Installation directory address -c nginx Profile address
#-c After the designation nginx Configuration file for
[root@node5 ~]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
# verification nginx Is the configuration file correct
[root@node5 ~]# /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
#Nginx,-s Adopt the direction of Nginx How to send a signal ,-s signal:send signal to a master process: stop, quit, reopen, reload
# The way to stop the step is to wait for nginx Process processing task completed to stop .
[root@node5 ~]# nginx -s quit
# This is equivalent to finding out nginx process id Reuse kill Order to force the killing process .
[root@node5 ~]# nginx -s stop
#Nginx Reload the configuration file ,-s Adopt the direction of Nginx How to send a signal
nginx -s reload
#nginx Stop operation is to nginx The process sends a signal
# step 1: Inquire about nginx Main process number
ps -ef | grep nginx
# In the process list Face search master process , Its number is the main process number .
# step 2: Sending signal
# Easy to stop Nginx:
kill -QUIT Main process number
# Stop quickly Nginx:
kill -TERM Main process number
# Force to stop Nginx:
pkill -9 nginx
# If in nginx.conf Configured with nginx.pid File storage path , be nginx.pid What's stored is Nginx Main process number , If not specified , By default, it is placed in nginx Of logs Under the table of contents , With nginx.pid file , We don't have to check Nginx The main process number of , Kill the process again . You can go directly to Nginx Sent a signal ,
# The order is as follows :kill - Signal type '/usr/nginx/logs/nginx.pid'
[root@node5 ~]# kill -9 /var/run/nginx/nginx.pid
# start-up
systemctl start nginx
# Check the status
systemctl status nginx
# stop it
systemctl stop nginx

Ten .nginx Configuration file details

1.nginx The main configuration file of is nginx.conf, Have a look first nginx.conf Default configuration file .# It starts with notes .

# Filter comments and blank lines in the configuration file
[root@node5 ~]# egrep -v "#|^$" /usr/local/nginx/conf/nginx.conf
#nginx Start user of / Group
user nginx;
# Number of work processes started , You can specify the starting fixed nginx Number of processes , Or use auto,auto It's starting with the current CPU Number of processes with the same thread , Such as CPU It's four cores and eight threads. It starts eight processes Nginx Working process .
worker_processes 2;
# Error log path
error_log /var/log/nginx/error.log;
error_log /var/log/nginx/error.log notice;
error_log /var/log/nginx/error.log info;
#Nginx Of PID route
pid /var/run/nginx/nginx.pid;
#events Modules mainly affect nginx Network connection between server and user , For example, whether to allow multiple network connections at the same time , Which event driven model is used to process requests , The maximum number of connections that each worker process can support at the same time , Whether to enable the serialization of network connections under multiple working processes .
events {
# Set up nginx The maximum number of concurrency that can be accepted
worker_connections 1024;
}
#http The module is Nginx An important part of server configuration , cache 、 Most functions such as proxy and log format definition and third-party modules can be set here ,http Blocks can contain more than one server block , And one server A block can contain more than one location block ,server Blocks can be configured to introduce 、MIME-Type Definition 、 Log customization 、 Is it enabled? sendfile、 The connection timeout and the maximum request limit for a single link .
http {
# File extension and file type mapping table
include mime.types;
# Default file type
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
# Whether to call sendfile function (zero copy --> zero copy The way ) To output the file , General application opens , Can greatly improve nginx Read file performance of , If the server is downloaded, it needs to be shut down .
sendfile on;
# Long connection timeout , The unit is seconds
keepalive_timeout 65;
#server modular , Set up a virtual machine host , Can contain their own overall situation fast , It can also contain more than one locating modular . For example, the port monitored by the virtual machine 、 The name of this virtual machine and IP To configure , Multiple server You can use a port , For example, they all use 80 Port supply web service .
server {
#server Global configuration for , Configure listening port
listen 80;
#server The name of , When accessing this name ,nginx Will call the current serevr The internal configuration process matches .
server_name localhost;
#location It's actually server An order of , by nginx The server provides more and more flexible instructions , It's all in location As reflected in , Mainly based on nginx Received request string , Requested for the user URL Match , And deal with specific instructions , The redirection address includes 、 Data caching and response control are implemented in this part , In addition, many third-party modules are configured in location Module configuration .
location / {
# Equivalent to the directory name of the default page , The default is relative path , You can use absolute path configuration .
root html;
index index.html index.htm;
}
# The file name of the error page
error_page 500 502 503 504 /50x.html;
#location Handle the corresponding page definition of different error codes to /50x.html, This corresponds to server Under the directory defined in .
location = /50x.html {
# Define the directory where the default page is located
root html;
}
}
}

2. binding Nginx Working process to different CPU On , Default Nginx There is no binding , Binding is not currently nginx Process monopolizes a core CPU, But it's guaranteed that the process won't run on other cores , This greatly reduces nginx The working process is different cpu Jump on , Less CPU Resource allocation and recycling of processes , So it can effectively improve nginx Server performance , The configuration is as follows :

# see CPU The number of cores
[root@node5 ~]# grep process /proc/cpuinfo | wc -l
4
# Four threads CPU Configuration of :
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
# Eight threads CPU Configuration of :
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

3.nginx Of PID file , Error log file path , Logging level related configuration :

# Appoint nginx Of PID File path
pid logs/nginx.pid;
# Specify the error log path
error_log logs/error.log;
# Specifies the logging level
error_log logs/error.log notice;
error_log logs/error.log info;
#nginx Log level supported :
# Log level syntax :
error_log file [ debug | info | notice | warn | error | crit ] | [{ debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_mail | debug_mysql } ]
The level of logging = Error log level | Debug log level ; perhaps
The level of logging = Error log level ;
#crit The minimum number of logs recorded , and debug Most of the logs are recorded . If your nginx Some problems , such as 502 More frequently , But look at the default error_log I didn't see any meaningful information , Then you can adjust the level of the error log , When you set it to error When level , The content of the error log will be more abundant .
# Level of error log : emerg, alert, crit, error, warn, notic, info, debug,
# Debug log level : debug_core, debug_alloc, debug_mutex, debug_event, debug_http, debug_mail, debug_mysql
#error_log Instruction log level configuration is divided into error log level and debug log level , Error log can only be set to one level , And the error log must be written before the debug log level , In addition, the debug log can be set at multiple levels , Other configuration methods may not meet the requirements .

4. Profile introduction :include

#file Is the file to import , Support relative path , Generally in html Inside the directory
include file;
# for example : Import a conf file , And configure pages with different host names , edit nginx.conf Master profile :
# Add an entry in the last brace ,* Is to import anything to conf Profile at the end
include /usr/local/nginx/conf.d/samsung.conf;
# stay /usr/local/nginx/conf.d/ Create a samsung.conf, The contents are as follows :
[root@node5 ~]# grep -v "#" conf.d/samsung.conf | grep -v "^$"
server {
listen 8090;
server_name samsung.chinacloudapp.cn;
location / {
root html;
index index1.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

11、 ... and .nginx performance tuning

1. Master profile nginx.conf Optimize

#nginx Start user of / Group
user nginx nginx;
#nginx Number of processes , It is suggested to follow cpu Number to specify , It's usually a multiple of it .
worker_processes 8;
# Assign... To each process cpu, take 8 Processes assigned to 8 individual cpu, Of course, you can write more than one , Or assign a process to multiple cpu.
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
# This instruction refers to a nginx The maximum number of file descriptors opened by the process , The theoretical value should be the maximum number of open files (ulimit -n) And nginx Divide the number of processes , however nginx Allocation requests are not so uniform , So it's better to be with ulimit -n Consistent values for .
# notes : You need to set ulimit -SHn 204800
worker_rlimit_nofile 204800;
events
{
# Use epoll Of I/O Model
use epoll;
# The maximum number of connections allowed per process , In theory, each one nginx The maximum number of connections to the server is worker_processes*worker_connections
worker_connections 204800;
}
http {
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;
charset utf-8;
server_names_hash_bucket_size 128;
# The buffer size of the client request header , This can be set according to the paging size of your system , Generally, the size of a request header does not exceed 1k, However, because the paging of general system is greater than 1k, So this is set to page size . Page size can be ordered getconf PAGESIZE obtain .
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 20m;
sendfile on;
tcp_nopush on;
#keepalive Timeout time
keepalive_timeout 60;
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
keys_zone=TEST:10m
inactive=5m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
# This will specify the cache for opening files , The default is not enabled ,max Specify the number of caches , It's recommended to be consistent with the number of open files ,inactive How long does it take to delete the cache after the file is not requested .
open_file_cache max=204800 inactive=20s;
#open_file_cache Directive inactive The minimum number of times a file is used in parameter time , If you exceed that number , File descriptors are always open in the cache , As in the above example , If there is a file in inactive Not used once in time , It will be removed .
open_file_cache_min_uses 1;
# This refers to how often to check the cached valid information .
open_file_cache_valid 30s;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
}

2. Optimization of kernel parameters

# Back up the initial kernel parameters
[root@node5 ~]# cp /etc/sysctl.conf /etc/sysctl.conf.bak
# Clear kernel parameters
[root@node5 ~]# > /etc/sysctl.conf
# Configure kernel parameters
[root@node5 ~]# vi /etc/sysctl.conf
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
# Turn on SYN Cookies, When there is a SYN Waiting for the queue to overflow , Enable cookies To deal with it .
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
#timewait The number of , The default is 180000.
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
# Each network interface receives packets faster than the kernel processes them , The maximum number of packets allowed to be sent to the queue .
net.core.netdev_max_backlog = 262144
#web Application listen Functional backlog Default will give us kernel parameters net.core.somaxconn Limit to 128, and nginx Defined NGX_LISTEN_BACKLOG The default is 511, So it's necessary to adjust this value .
net.core.somaxconn = 262144
# How many at most in the system TCP Socket is not associated with any user file handle . If you exceed that number , The orphan connection will now be reset and a warning message printed . This limitation is only to prevent simple DoS attack , You can't rely too much on it or artificially reduce this value , This value should be increased ( If you add more memory ).
net.ipv4.tcp_max_orphans = 3276800
# The maximum number of connection requests recorded that have not yet received a client acknowledgement . For having 128M Memory system , The default value is 1024, The system with small memory is 128.
net.ipv4.tcp_max_syn_backlog = 262144
# Timestamps can avoid the winding of serial numbers . One 1Gbps The link of is sure to encounter the serial number that has been used before . Timestamps allow the kernel to accept this “ abnormal ” Data packets of . You need to turn it off .
net.ipv4.tcp_timestamps = 0
# In order to open the end-to-end connection , The kernel needs to send a SYN With a response to the previous one SYN Of ACK. That is to say, the second handshake in the three handshakes . This setting determines the kernel to send before it drops the connection SYN+ACK The number of bags .
net.ipv4.tcp_synack_retries = 1
# Send... Before the kernel abandons the connection SYN The number of bags .
net.ipv4.tcp_syn_retries = 1
# Enable timewait Quick recovery .
net.ipv4.tcp_tw_recycle = 1
# Enable reuse . Allows you to TIME-WAIT sockets Reapply to new TCP Connect .
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
# If the socket is closed by the local request , This parameter determines that it stays at FIN-WAIT-2 Time of state . The peer can fail and never close the connection , Even crashed unexpectedly . The default value is 60 second .2.2 The usual value of the kernel is 180 second , You can press this setting , But remember , Even if your machine is a light load WEB The server , There is also a risk of memory overflow due to a large number of dead sockets ,FIN- WAIT-2 The risk ratio of FIN-WAIT-1 smaller , Because it can only eat 1.5K Memory , But they live longer .
net.ipv4.tcp_fin_timeout = 1
# When keepalive When it comes to use ,TCP send out keepalive The frequency of the news . The default is 2 Hours .
net.ipv4.tcp_keepalive_time = 30
# The range of ports that the system is allowed to open
net.ipv4.ip_local_port_range = 1024 65000
# Save kernel parameters
[root@node5 ~]# sysctl -p

3.FastCGI Parameter optimization

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m;
The order is FastCGI The cache specifies a path , Directory structure level , Key area storage time and inactive delete time .
fastcgi_connect_timeout 300;
Specify the connection to the back end FastCGI Timeout for .
fastcgi_send_timeout 300;
towards FastCGI Timeout for transmitting request , This value means that the handshake has been completed twice and the handshake is backward FastCGI Timeout for transmitting request .
fastcgi_read_timeout 300;
receive FastCGI Timeout for response , This value refers to the received after two handshakes FastCGI Timeout for response .
fastcgi_buffer_size 16k;
Specify read FastCGI How much buffer is needed for the first part of the response , This can be set to fastcgi_buffers The buffer size specified by the instruction , The instruction above specifies that it will use 1 individual 16k To read the first part of the reply , That's the response header , In fact, this response header is usually very small ( Not more than 1k), But if you're in fastcgi_buffers The size of the buffer is specified in the instruction , Then it will also allocate a fastcgi_buffers Specified buffer size to cache .
fastcgi_buffers 16 16k;
Specifies how many and how many buffers are needed locally to buffer FastCGI Response to , As shown above , If one php The page size generated by the script is 256k, Will be allocated to them 16 individual 16k Buffer to cache , If it is greater than 256k, Increase is greater than 256k The part of will be cached to fastcgi_temp In the specified path , Of course, this is an unwise solution for server load , Because the speed of processing data in memory is faster than that of hard disk , Usually, this value should be set in your site php The middle value of the page size generated by the script , For example, most of your site's scripts produce a page size of 256k You can set this value to 16 16k, perhaps 4 64k perhaps 64 4k, But clearly , The latter two are not good settings , Because if the generated page is only 32k, If you use 4 64k It will allocate 1 individual 64k Buffer to cache , And if you use 64 4k It will allocate 8 individual 4k Buffer to cache , And if you use 16 16k Then it allocates 2 individual 16k To cache pages , It seems more reasonable .
fastcgi_busy_buffers_size 32k;
I don't know what this order is for , I only know that the default value is fastcgi_buffers Twice as many .
fastcgi_temp_file_write_size 32k;
In the writing fastcgi_temp_path How large data blocks will be used , The default value is fastcgi_buffers Twice as many .
fastcgi_cache TEST
Turn on FastCGI Cache and give it a name . I think it's very useful to open the cache , Can effectively reduce CPU load , And prevent 502 error . But this cache can cause a lot of problems , Because it caches dynamic pages . Specific use also needs to be based on their own needs .
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
Specifies the cache time for the specified reply code , As will be shown in the above example 200,302 Answer cache for one hour ,301 Answer cache 1 God , For the other 1 minute .
fastcgi_cache_min_uses 1;
cached fastcgi_cache_path Instructions inactive The minimum number of times to use the parameter value in time , As in the above example , If in 5 A file in minutes 1 It's not used , Then this file will be removed .
fastcgi_cache_use_stale error timeout invalid_header http_500;
I don't know the function of this parameter , The guess should be to let nginx It's useless to know what type of cache is . The above is nginx in FastCGI Related parameters , in addition ,FastCGI There are also some configurations that need to be optimized , If you use php-fpm To manage FastCGI, You can modify the following values in the configuration file :
<value name="max_children">60</value>
Number of concurrent requests processed at the same time , That is, it will turn on at most 60 Sub threads to handle concurrent connections .
<value name="rlimit_files">102400</value>
Maximum number of open files .
<value name="max_requests">204800</value>
The maximum number of requests that can be executed by each process before reset .

Twelve .nginx Solutions to common problems

12.1 Normal users start , restart , Reload nginx It's a mistake :

1. When we use ordinary users start,restart,reload nginx When the following error occurs :

nginx@node5 ~]$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /usr/local/nginx/conf/nginx.conf:1
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)

2. The reason for this problem is : stay Linux in 1024 The following ports , Only root Only the user has the right to occupy .

3. resolvent :

Method 1 : The settings are only root and nginx The user can only start nginx( recommend )

#nginx The user is nginx Start user of
[nginx@node5 ~]$ id nginx
uid=8000(nginx) gid=8000(nginx) groups=8000(nginx)
# Set up nginx The owner of the directory is root, The group owner is nginx
[root@node5 ~]# chown -R root:nginx /usr/local/nginx
[root@node5 ~]# ll /usr/local/nginx/ -d
drwxr-xr-x 5 root nginx 42 Oct 22 16:14 /usr/local/nginx/
[root@node5 ~]# chmod -R 750 /usr/local/nginx
# To the executable nginx Set up SUID jurisdiction , such nginx User start nginx You'll get it temporarily root jurisdiction , About SUID Please check out “ Special permissions for files ” chapter
[root@node5 ~]# chmod u+s /usr/local/nginx/sbin/nginx
[root@node5 ~]# su nginx
[nginx@node5 root]$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
# You can see that ordinary users can also start nginx 了
[nginx@node5 root]$ ps -ef | grep nginx
root 63296 61383 0 16:22 pts/0 00:00:00 su nginx
nginx 63297 63296 0 16:22 pts/0 00:00:00 bash
root 63345 1 0 16:23 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 63346 63345 0 16:23 ? 00:00:00 nginx: worker process
nginx 63347 63345 0 16:23 ? 00:00:00 nginx: worker process
nginx 63385 63297 0 16:24 pts/0 00:00:00 ps -ef
nginx 63386 63297 0 16:24 pts/0 00:00:00 grep --color=auto nginx
[nginx@node5 root]$ /usr/local/nginx/sbin/nginx -s quit
[nginx@node5 root]$ ps -ef | grep nginx
root 63296 61383 0 16:22 pts/0 00:00:00 su nginx
nginx 63297 63296 0 16:22 pts/0 00:00:00 bash
nginx 63470 63297 0 16:25 pts/0 00:00:00 ps -ef
nginx 63471 63297 0 16:25 pts/0 00:00:00 grep --color=auto nginx

Method 2 : Set up that all users can start nginx( Not recommended )

[root@node5 ~]# chown -R root:root /usr/local/nginx
[root@node5 ~]# chmod -R 755 /usr/local/nginx
[root@node5 ~]# chmod u+s /usr/local/nginx/sbin/nginx

Method 3 : Use sudo Administrator rights start nginx, To perform this method , Must ensure nginx Users have sudo jurisdiction , About sudo Permission configuration details , Please check out “ Configure for ordinary users sudo jurisdiction ” chapter

[nginx@node5 ~]$ sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
[nginx@node5 ~]$ ps -ef | grep nginx
root 111427 94811 0 15:46 pts/1 00:00:00 su - nginx
nginx 111428 111427 0 15:46 pts/1 00:00:00 -bash
root 111628 1 0 15:49 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 111629 111628 0 15:49 ? 00:00:00 nginx: worker process
nginx 111630 111628 0 15:49 ? 00:00:00 nginx: worker process
nginx 111637 111428 0 15:49 pts/1 00:00:00 ps -ef
nginx 111638 111428 0 15:49 pts/1 00:00:00 grep --color=auto nginx

13、 ... and . To the installed nginx Add a new module

13.1 The problem background

​ Generally speaking , We will compile on demand according to project requirements and business requirements nginx, But over time ,nginx The existing modules may no longer meet the existing business requirements

了 , At this point, we need to talk to nginx Add new modules dynamically , To meet the needs .

13.2 To already installed nginx Add a new module

1. Prerequisites for this step : It has been compiled and installed before nginx, And now it's running .

2. To the installed nginx Ideas for adding new modules : Use with existing nginx The same version of the source package , Add a new module and recompile nginx Source code , Then compile the nginx Enforceability

Line file replaces the existing nginx Executable file .

3.nginx Add new module command format :

./configure Parameters --add-module= New modules

4. To the installed nginx Add a new module , This time add ngx_http_google_filter_module Module as an example ,ngx_http_google_filter_module It's a filter mold

block , Can make Google image more convenient to deploy . Built in regular expressions 、URI locations And other complex configurations . Native nginx Modules ensure more efficient processing of

cookies, gstatic scoures Redirection .

# Use Git download ngx_http_google_filter_module modular
[root@node5 ~]# git clone https://github.com/cuber/ngx_http_google_filter_module
[root@node5 ~]# git clone https://github.com/yaoweibin/ngx_http_substitutions_filter_module
# see nginx Version number and detailed compilation parameters of
[root@node5 ~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
# Decompression is as like as two peas nginx Source package
[root@node5 ~]# tar xf nginx-1.19.3.tar.gz
[root@node5 ~]# cd nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src
[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3
# Clear the last time make The command produces object and Makefile file . Use scenarios : When it needs to be re executed configure when , You need to perform make clean
[root@node5 nginx-1.19.3]# make clean
rm -rf Makefile objs
# Check the compilation environment ,
[root@node5 nginx-1.19.3]# ./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=/root/ngx_http_google_filter_module --add-module=/root/ngx_http_substitutions_filter_module
# Output is 0, It means that the last step was successful
[root@node5 nginx-1.19.3]# echo $?
0
# compile
[root@node5 nginx-1.19.3]# make -j 4
# Output is 0, It means that the last step was successful
[root@node5 nginx-1.19.3]# echo $?
0
# Back up the original nginx Executable file
[root@node5 nginx-1.19.3]# mv /usr/local/nginx/sbin/nginx{,`date +%F-%T`}
[root@node5 nginx-1.19.3]# ll objs/nginx
-rwxr-xr-x 1 root root 6370448 Oct 30 16:55 objs/nginx
# Use the new nginx Executable file
[root@node5 nginx-1.19.3]# cp objs/nginx /usr/local/nginx/sbin/
#nginx -t Check if the configuration file is correct
[root@node5 nginx-1.19.3]# /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
# see nginx Version number and detailed compilation parameters of , From the output we can see , New modules have been added
[root@node5 nginx-1.19.3]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=/root/ngx_http_google_filter_module --add-module=/root/ngx_http_substitutions_filter_module
[root@node5 nginx-1.19.3]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
[root@node5 nginx-1.19.3]# ps -ef | grep nginx
root 36630 1 0 17:03 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx 36631 36630 0 17:03 ? 00:00:00 nginx: worker process
nginx 36632 36630 0 17:03 ? 00:00:00 nginx: worker process
root 36641 27402 0 17:03 pts/2 00:00:00 grep --color=auto nginx
#curl nginx port , Enter the following description nginx Function is normal
[root@node5 nginx-1.19.3]# curl http://localhost
<!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>

Reference link :

https://www.cnblogs.com/stulzq/p/9291223.html

https://www.jiangexing.cn/355.html

https://blog.csdn.net/lxw1844912514/article/details/104738967/

https://www.linuxidc.com/Linux/2017-02/140495.htm

https://www.linuxidc.com/Linux/2013-09/89656.htm

版权声明
本文为[Philosophy of life]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple