Detailed explanation of Nginx website service (compilation, installation and system service addition)

Table of contents

1. Nginx related knowledge

1) Introduction to Nginx

Nginx:

Apache:

2) The difference between Apache and Nginx 

Advantages of Nginx over Apache: 

Advantages of apache over nginx:

3) Nginx process  

Nginx has two processes:

How does Nginx achieve high concurrency? 

synchronous and asynchronous

blocking and non-blocking

Why doesn't Nginx use multithreading?

2. Compile and install Nginx service

1) Preliminary compilation and installation

①Turn off the firewall, and transfer the software package required to install nginx to the /opt directory

2) Install related dependencies

3) Create user groups and compile and install

2) Initial command of Nginx 

①Start the Nginx service

② Stop nginx service

In addition: there are many ways to view the nginx process number

③Reload nginx service

④ Log segmentation, reopen the log file

​edit

⑤Smooth upgrade 

3) Add nginx to system services 

Method 1: script method

Method 2: Add nginx service configuration in the main service (/lib/systemd/system/)


1. Nginx related knowledge

1) Introduction to Nginx

Nginx:

  • Nginx is an open-source, high-performance, highly reliable web and reverse proxy server, and it supports hot deployment. It can run almost 7 * 24 hours a day without restarting even if it runs for several months. Hot update of software version in case of service
  • High processing capacity for HTTP concurrent connections, a single physical server can support 30,000~50,000 concurrent requests. (In actual operation, many companies will set it at about 20,000 for the stability of the server)
     

The main usage scenarios of Nginx: virtual host, reverse proxy, cache, http  

Apache:

Apache is a process-based structure. Processes consume more system overhead than threads, and are not suitable for multi-processor environments. Therefore, when an apache Web site expands, it is usually to increase servers or expand cluster nodes instead of increasing processor 

2) The difference between Apache and Nginx 

Nginx Apache
nginx is an event-based web server Apache is a process-based server
All requests are handled by one thread A single thread handles a single request
nginx avoids the concept of child processes Apache is based on subprocess
nginx is similar to speed apache is similar to power
nginx is better in terms of memory consumption and connections apache does not improve on memory consumption and connections
nginx performs better in load balancing When the traffic reaches the process limit, apache will refuse new connections.
Nginx does not support the same os as IBMI and openvms Apache supports more os
nginx only has core functions apache provides more features than nginx
nginx performance and scalability do not depend on hardware Apache depends on hardware components such as cpu and memory
Nginx supports hot deployment Apache does not support hot deployment

Advantages of Nginx over Apache: 

  • Lightweight, nginx takes up less memory and resources than apache

  • Static processing, Nginx static processing performance is higher than Apache 

  • Nginx can achieve cache-free reverse proxy acceleration and improve website speed

  • Nginx performance and scalability do not depend on hardware, Apache depends on hardware

  • Nginx supports hot deployment, starts quickly, and can upgrade the software version or configuration without interrupting the service

  • Nginx is an asynchronous process, and multiple connections can correspond to one process; Apache is a synchronous multi-process, and one connection corresponds to one process

  • Nginx is highly modular, relatively simple to write modules, and has fewer components than Apache

  • Under high concurrency, nginx can maintain low resource consumption and high performance

  • Nginx configuration is simple, Apache configuration is complex

Advantages of apache over nginx:

  • Rewrite is more powerful than nginx's rewrite (the main function of rewrite is to realize the jump of uniform resource locator URL)
  • There are many modules, you can find almost everything you think of
  • Less bugs, nginx has relatively more bugs
  • super stable
  • Nginx is weak in handling dynamic requests, and Apache needs to do dynamic requests

3) Nginx process  

The default ports of both Apache and Nginx are 80. When you first find that Nginx fails to start, the reason may be that port 80 is occupied, which causes the service to fail to start. You can modify the port of the service to realize the simultaneous operation of the two services.

Nginx has two processes:

master process: the main process (daemon process), used to manage the worker process

Worker process: Worker process, used to process user requests

How does Nginx achieve high concurrency? 

  • Asynchronous, non-blocking, using epoll and a lot of underlying code optimization
  • If a server adopts the method that one process is responsible for one request, then the number of processes is the number of concurrency. Under normal circumstances, there will be many processes waiting
  • And nginx adopts the mode of one master process and multiple woker processes
  • The master process is mainly responsible for collecting and distributing requests. Whenever a request comes, the master pulls up a worker process to handle the request. At the same time, the master process is also responsible for monitoring the status of the woker to ensure high reliability
  • The woker process is generally set to match the number of CPU cores. The number of requests that nginx's woker process can handle at the same time is only limited by memory, and can handle multiple requests
  • Nginx's asynchronous non-blocking working method is taking advantage of the waiting time. When there is a need to wait, these processes are idle and on standby, so a small number of processes can solve a large number of concurrency problems

synchronous and asynchronous

  • Synchronization: When the completion of a service depends on other services, it is considered complete only after the dependent service is completed. This is a reliable service sequence. Either success is successful or failure is failure, and the state of the service can be kept consistent
  • Asynchronous: When the completion of a service depends on other services, it only notifies other dependent services to start execution without waiting for the dependent service to complete. At this point, the service is complete. Whether the dependent service is finalized cannot be determined, so it is an unreliable service sequence

blocking and non-blocking

  • Blocking: Blocking calls mean that the current thread will be suspended before the call result is returned, waiting for message notifications, unable to perform other services, and the function will only return after the result is obtained.
  • Non-blocking: The concept of non-blocking corresponds to blocking, which means that the function will not block the current thread before the result can not be obtained immediately, but will return immediately

Why doesn't Nginx use multithreading?

  • Apache: Create multiple processes or threads, and each process or thread will allocate cpu and memory for it (threads are much smaller than processes, so workers support higher concurrency than perfork), and excessive concurrency will consume server resources
  • Nginx: Use single thread to process requests asynchronously and non-blockingly (the administrator can configure the number of working processes of the Nginx main process) (epoll), and will not allocate cpu and memory resources for each request, saving a lot of resources and reducing Lots of CPU context switching. That's why Nginx supports higher concurrency

2. Compile and install Nginx service

1) Preliminary compilation and installation

①Turn off the firewall, and transfer the software package required to install nginx to the /opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

2) Install related dependencies

#nginx的配置及运行需要pcre、zlib、openssl等软件包的支持,因此需要安装这些软件的开发包,以便提供相应的库和头文件。
yum -y install pcre-devel zlib-devel openssl-devel gcc gcc-c++ make

3) Create user groups and compile and install

[root@localhost opt]#useradd -M -s /sbin/nologin nginx
 
[root@localhost opt]#tar zxvf nginx-1.12.2.tar.gz -C /opt/
 
[root@localhost opt]#cd nginx-1.12.2/
[root@localhost nginx-1.12.2]#./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-http_stub_status_module

make && make install
 
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/		#让系统识别nginx的操作命令

2) Initial command of Nginx 

①Start the Nginx service

#检查nginx服务配置是否正确
nginx  -t
#启动nginx服务
/usr/local/sbin/nginx
#快捷运行
nginx

② Stop nginx service

cat /usr/local/nginx/logs/nginx.pid		#先查看nginx的PID号
kill -3 <PID号>
kill -s QUIT <PID号>
killall -3 nginx
killall -s QUIT nginx

In addition: there are many ways to view the nginx process number

cat /usr/local/nginx/logs/nginx.pid   //查看nginx主进程的PID
 
pgrep nginx -l   //查看nginx的主进程号和工作进程号
 
lsof -i :80    //查看nginx的主进程号和工作进程号
ss -ntap | grep nginx  //查看nginx的主进程号和工作进程号
netstat -ntap | grep nginx  //查看nginx主进程的PID
 

③Reload nginx service

kill -1 <PID号>
kill -s HUP <PID号>
killall -1 nginx
killall -s HUP nginx

④ Log segmentation, reopen the log file

[root@localhost logs]#ls
access.log  error.log  nginx.pid
[root@localhost logs]#mv access.log    access.`date +%F`.log
[root@localhost logs]#ls
access.2022-09-27.log  error.log  nginx.pid
[root@localhost logs]#kill -USR1 8468
[root@localhost logs]#ls
access.2022-09-27.log  access.log  error.log  nginx.pid
[root@localhost logs]#

⑤Smooth upgrade 

Introducing new upgrade packages:

tar -zxvf nginx-1.22.0.tar.gz 
cd nginx-1.22.0
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module
--with-http_ssl_module

Compile and install the new nginx upgrade package:

#编译安装
make
#将老版本的nginx进行备份,防止升级失败,还原
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_old
#将新的运行文件放入安装的运行目录
cp objs/nginx /usr/local/nginx/sbin/nginx

Smooth upgrade:

make
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_old
cp objs/nginx /usr/local/nginx/sbin/nginx
make upgrade  

3) Add nginx to system services 

When we use the service installed by yum, the general startup method is: systemctl service name operation. For nginx after source code installation, it cannot be used directly like this. So we can implement the startup method of system services through scripts or changes in system services

Method 1: script method

vim /etc/init.d/nginx

#!/bin/bash
# chkconfig: 35 22 88
# description: This is nginx service control script

cmd="/usr/local/nginx/sbin/nginx"
pidfile="/usr/local/nginx/logs/nginx.pid"
count=$(pgrep -c nginx | grep -v "service|grep|$$" | grep -c "nginx")

case "$1" in
start)
    if [[ $count -ge 1 ]]; then
        echo "Nginx 已经启动....."
    else
        echo "Nginx 正在启动....."
        nohup $cmd >dev/null 2>&1 &
    fi
    ;;
stop)
    kill -QUIT $(cat $pidfile)
    ;;
restart)
    $0 stop
    $0 start
    ;;
reload)
    kill -HUP $(cat $pidfile)
    ;;
status)
    if [[ $count -ge 1 ]]; then
        echo "Nginx is running......"
    fi
    ;;
*)
    echo "Usage: $0 {start|stop|restart|reload|status}"
    exit 1
    ;;
esac

exit 0

  

chmod +x /etc/init.d/nginx
chkconfig --add nginx						
service nginx status

Method 2: Add nginx service configuration in the main service (/lib/systemd/system/)

Preparation before experiment:

[root@localhost init.d]#mkdir nginx.old
[root@localhost init.d]#mv nginx   ./nginx.old/

  

Failed to start (successfully removed the server startup mode), execute the second method

vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
[root@localhost init.d]#vim /lib/systemd/system/nginx.service
[root@localhost init.d]#chmod 754 /lib/systemd/system/nginx.service
[root@localhost init.d]#systemctl daemon-reload
[root@localhost init.d]#systemctl start nginx
[root@localhost init.d]#systemctl status nginx

Guess you like

Origin blog.csdn.net/qq_21003381/article/details/130967338