Nginx介绍

Nginx的基本功能

  • 静态资源的Web服务器
  • http协议反向代理服务器

Nginx模块

Nginx高度模块化,其模块可以分为以下三类:

  • 核心模块:Core functionality
  • 标准模块
    • HTTP模块:ngx_http_xxx
    • Mail模块:ngx_mail_xxx
    • Stream模块:ngx_stream_xxx
  • 第三方模块:ngx_google_perftools_module

在这里插入图片描述

Nginx安装和使用

在这里插入图片描述
在这里插入图片描述
CentOS8安装Nginx有以下步骤,详细安装过程可查看视频

  • 第一步,执行命令:yum install yum-utils,安装yum-utils模块。yum-utils是管理repository及扩展包的工具。
[root@localhost ~]# yum install yum-utils
Last metadata expiration check: 1:17:05 ago on Fri 13 Aug 2021 08:42:06 PM CST.
Package yum-utils-4.0.18-4.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!
  • 第二步,编辑nginx.repo文件。
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# vim nginx.repo

nginx.repo中填入如下内容:

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
  • 第三步,执行命令:yum install nginx,安装Nginx。
[root@localhost yum.repos.d]# yum install nginx
nginx stable repo                                                       4.0 kB/s |  30 kB     00:07    
Last metadata expiration check: 0:00:06 ago on Fri 13 Aug 2021 09:59:53 PM CST.
Dependencies resolved.
========================================================================================================
 Package            Architecture        Version                         Repository                 Size
========================================================================================================
Installing:
 nginx              x86_64              1:1.20.1-1.el8.ngx              nginx-stable              819 k

Transaction Summary
========================================================================================================
Install  1 Package

Total download size: 819 k
Installed size: 2.8 M
Is this ok [y/N]: y
Downloading Packages:
nginx-1.20.1-1.el8.ngx.x86_64.rpm                                        34 kB/s | 819 kB     00:24    
--------------------------------------------------------------------------------------------------------
Total                                                                    34 kB/s | 819 kB     00:24     
warning: /var/cache/dnf/nginx-stable-614ef03fac352fea/packages/nginx-1.20.1-1.el8.ngx.x86_64.rpm: Header V4 RSA/SHA1 Signature, key ID 7bd9bf62: NOKEY
nginx stable repo                                                       1.1 kB/s | 1.5 kB     00:01    
Importing GPG key 0x7BD9BF62:
 Userid     : "nginx signing key <signing-key@nginx.com>"
 Fingerprint: 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
 From       : https://nginx.org/keys/nginx_signing.key
Is this ok [y/N]: y
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                1/1 
  Running scriptlet: nginx-1:1.20.1-1.el8.ngx.x86_64                                                1/1 
  Installing       : nginx-1:1.20.1-1.el8.ngx.x86_64                                                1/1 
  Running scriptlet: nginx-1:1.20.1-1.el8.ngx.x86_64                                                1/1 
----------------------------------------------------------------------

Thanks for using nginx!

Please find the official documentation for nginx here:
* https://nginx.org/en/docs/

Please subscribe to nginx-announce mailing list to get
the most important news about nginx:
* https://nginx.org/en/support.html

Commercial subscriptions for nginx are available on:
* https://nginx.com/products/

----------------------------------------------------------------------

  Verifying        : nginx-1:1.20.1-1.el8.ngx.x86_64                                                1/1 
Installed products updated.

Installed:
  nginx-1:1.20.1-1.el8.ngx.x86_64                                                                       

Complete!
  • 第四步,执行命令:yum info nginx,检查安装的Nginx信息。
[root@localhost yum.repos.d]# yum info nginx
Last metadata expiration check: 0:00:52 ago on Fri 13 Aug 2021 09:59:53 PM CST.
Installed Packages
Name         : nginx
Epoch        : 1
Version      : 1.20.1
Release      : 1.el8.ngx
Architecture : x86_64
Size         : 2.8 M
Source       : nginx-1.20.1-1.el8.ngx.src.rpm
Repository   : @System
From repo    : nginx-stable
Summary      : High performance web server
URL          : https://nginx.org/
License      : 2-clause BSD-like license
Description  : nginx [engine x] is an HTTP and reverse proxy server, as well as
             : a mail proxy server.

Nginx的进程

rpm -ql nginx,查看Nginx安装了哪些文件。

[root@localhost ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/.build-id
/usr/lib/.build-id/1d
/usr/lib/.build-id/1d/3ae6e2bbd9ecc1b968a5b9272ba0f431827ac1
/usr/lib/.build-id/e8
/usr/lib/.build-id/e8/4bc53181babc7ef9cb59c1239522ffe45d375b
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.20.1
/usr/share/doc/nginx-1.20.1/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx

其中,/usr/sbin/nginx是Nginx的主进程。

[root@localhost ~]# which nginx
/usr/sbin/nginx

nginx的启停

  • 第一种启停止方式
    nginx,启动nginx;
    nginx -s stop,停止nginx。
  • 第二种启停方式
    systemctl start nginx,启动nginx;
    systemctl stop nginx,停止nginx。

Nginx的配置

配置文件的结构

主配置文件:/etc/nginx/nginx.conf
子配置文件:/etc/nginx/conf.d/*.conf

# 主配置段,即全局配置段,对http、mail、stream都有效
main block

# http/https 协议相关配置段
http {
}

# mail 协议相关配置段
mail {
}

# stream服务器相关配置段
stream{
}
http协议的相关配置

http {
  # 各个server的公共配置
  #
  #每个server用于定义一个虚拟机
  server {

  }
  server {
    server_name 虚拟主机名
    root        主目录
    alias       路径别名
    location [OPTITION] URL {

    }
  }
}
server

更多指令详见ngx_http_core_module模块。

server{
	listen  监听端口;
	server_name  虚拟主机名;
	root  主目录;
}

来看下nginx.conf中的内容,如下:

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

配置文件中的指令以分号结尾。
现在我们对nginx.conf进行修改,在http包含块的最后一行添加:include /ect/nginx/conf.d/vhost/*.conf,即

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/conf.d/vhosts/*.conf;
}

为此,我们在新建目录vhosts,并在vhosts目录下新建a.com.confb.com.conf


[root@localhost ~]# cd /etc/nginx/conf.d/
[root@localhost conf.d]# mkdir vhost
[root@localhost conf.d]# cd vhosts
[root@localhost vhosts]# vim a.com.conf
[root@localhost vhosts]# vim b.com.conf

其中,
a.com.conf内容如下:

server {
        listen 80;
        server_name www.a.com;
        root /data/sitea;
}

b.com.conf内容如下:

server{
        listen 8080;
        server_name www.b.com;
        root /data/siteb;
}

为保证以上修改生效,依次执行命令nginx -s stopnginx以重启nginx。

为了能够访问www.a.comwww.b.com,在/etc/hosts添加192.168.21.128 www.a.com www.b.com,即

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.21.128 www.a.com www.b.com

使用curl访问www.a.com

[root@localhost ~]# curl www.a.com
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

返回404

因为www.a.com的主目录是/data/siteawww.b.com的主目录是/data/siteb,但当前并没有/data目录。于是,

[root@localhost ~]# mkdir /data/site{a,b} -pv
mkdir: created directory '/data'
mkdir: created directory '/data/sitea'
mkdir: created directory '/data/siteb'
[root@localhost ~]# echo welcome to www.a.com > /data/sitea/index.html
[root@localhost ~]# echo welcome to www.b.com > /data/siteb/index.html
[root@localhost ~]# curl www.a.com
welcome to www.a.com
[root@localhost ~]# curl www.b.com:8080
welcome to www.b.com
全局配置指令
user

user,指定worker进程的运行身份,如果不指定组,则默认组名与用户名同名。
user nginx;,见上述/etc/nginx/nginx.conf

  • 启动nginx前,执行ss -ntl
[root@localhost nginx]# ss -ntl
State                Recv-Q               Send-Q                              Local Address:Port                               Peer Address:Port
LISTEN               0                    128                                       0.0.0.0:111                                     0.0.0.0:*
LISTEN               0                    32                                  192.168.122.1:53                                      0.0.0.0:*
LISTEN               0                    128                                       0.0.0.0:22                                      0.0.0.0:*
LISTEN               0                    5                                       127.0.0.1:631                                     0.0.0.0:*
LISTEN               0                    128                                     127.0.0.1:6010                                    0.0.0.0:*
LISTEN               0                    128                                          [::]:111                                        [::]:*
LISTEN               0                    128                                          [::]:22                                         [::]:*
LISTEN               0                    5                                           [::1]:631                                        [::]:*
LISTEN               0                    128                                         [::1]:6010                                       [::]:*
  • 启动nginx后,执行ss -ntl
[root@localhost nginx]# ss -ntl
State                Recv-Q               Send-Q                              Local Address:Port                               Peer Address:Port
LISTEN               0                    128                                       0.0.0.0:111                                     0.0.0.0:*
LISTEN               0                    128                                       0.0.0.0:80                                      0.0.0.0:*
LISTEN               0                    32                                  192.168.122.1:53                                      0.0.0.0:*
LISTEN               0                    128                                       0.0.0.0:22                                      0.0.0.0:*
LISTEN               0                    5                                       127.0.0.1:631                                     0.0.0.0:*
LISTEN               0                    128                                     127.0.0.1:6010                                    0.0.0.0:*
LISTEN               0                    128                                          [::]:111                                        [::]:*
LISTEN               0                    128                                          [::]:22                                         [::]:*
LISTEN               0                    5                                           [::1]:631                                        [::]:*
LISTEN               0                    128                                         [::1]:6010                                       [::]:*

nginx启动后,80端口也起来了。

  • 继续执行ps -aux|grep nginx
[root@localhost nginx]# ps -aux | grep nginx
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        4807  0.0  0.1   9676  2140 pts/1    T    16:34   0:00 less nginx.conf
root        5528  0.0  0.0  42732   880 ?        Ss   17:04   0:00 nginx: master process nginx
nginx       5529  0.0  0.2  77460  5124 ?        S    17:04   0:00 nginx: worker process
nginx       5530  0.0  0.2  77460  5084 ?        S    17:04   0:00 nginx: worker process
nginx       5531  0.0  0.2  77460  5164 ?        S    17:04   0:00 nginx: worker process
nginx       5532  0.0  0.2  77460  5164 ?        S    17:04   0:00 nginx: worker process
root        5676  0.0  0.0  12112  1000 pts/1    S+   17:10   0:00 grep --color=auto nginx

在这里插入图片描述

  • 修改/etc/nginx/nginx.conf,将user设置为nobody,并nginx -s reload以重新加载配置文件。
    在这里插入图片描述
  • 再次执行ps -aux | grep nginx
[root@localhost run]# ps -aux | grep nginx
root        2921  0.0  0.1  42864  3236 ?        Ss   18:25   0:00 nginx: master process nginx
nobody      3375  0.0  0.2  77604  5036 ?        S    18:57   0:00 nginx: worker process
nobody      3376  0.0  0.2  77604  4972 ?        S    18:57   0:00 nginx: worker process
nobody      3377  0.0  0.2  77604  5060 ?        S    18:57   0:00 nginx: worker process
nobody      3378  0.0  0.2  77604  5072 ?        S    18:57   0:00 nginx: worker process
root        3380  0.0  0.0  12112   976 pts/1    S+   18:57   0:00 grep --color=auto nginx
pid

pid,指定存储master进程pid的文件路径。
pid /var/run/nginx.pid,见上述/etc/nginx/nginx.conf

[root@localhost run]# ps -aux|grep nginx
root        3402  0.0  0.1  42864  3456 ?        Ss   18:59   0:00 nginx: master process nginx
nginx       3438  0.0  0.2  77596  5320 ?        S    19:01   0:00 nginx: worker process
nginx       3439  0.0  0.2  77596  5320 ?        S    19:01   0:00 nginx: worker process
nginx       3440  0.0  0.2  77596  5236 ?        S    19:01   0:00 nginx: worker process
nginx       3441  0.0  0.2  77596  5252 ?        S    19:01   0:00 nginx: worker process
root        3474  0.0  0.0  12112   992 pts/1    S+   19:03   0:00 grep --color=auto nginx
[root@localhost run]# cat /var/run/nginx.pid
3402
include

include,指明包含进来的其他配置文件片段。

load_module

load_module

性能优化相关的配置
worker_processes

worker_processes number|auto,worker进程的数量,通常应该为当前主机的cpu的物理核心数。

  • 通过lscpu查看得知,CPU(s): 4,即本机有4个cpu。由于/etc/nginx/nginx.confworker_processes auto;,所以worker进程有4个。
[root@localhost nginx]# lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  1
Core(s) per socket:  1
Socket(s):           4
NUMA node(s):        1
Vendor ID:           AuthenticAMD
CPU family:          23
Model:               96
Model name:          AMD Ryzen 5 4600H with Radeon Graphics
Stepping:            1
CPU MHz:             2994.376
BogoMIPS:            5988.75
Hypervisor vendor:   VMware
Virtualization type: full
L1d cache:           32K
L1i cache:           32K
L2 cache:            512K
L3 cache:            4096K
NUMA node0 CPU(s):   0-3
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves clzero wbnoinvd arat umip rdpid overflow_recov succor
[root@localhost nginx]# pstree -p | grep nginx
           |-nginx(3402)-+-nginx(3438)
           |             |-nginx(3439)
           |             |-nginx(3440)
           |             `-nginx(3441)
[root@localhost nginx]#
  • ps axo pid,cmd,psr | grep nginx,查看系统中nginx进程的进程号(pid)、进程名(cmd)和进程运行在哪个cpu上(psr)。
[root@localhost nginx]# ps axo pid,cmd,psr | grep nginx
   2854 nginx: master process nginx   2
   2855 nginx: worker process         3
   2856 nginx: worker process         1
   2857 nginx: worker process         1
   2858 nginx: worker process         2
   4521 grep --color=auto nginx       1

我们不妨修改下配置文件nginx.conf,将worker _processes设置为2,也就是说,只有两个worker进程。

[root@localhost nginx]# ps axo cmd,pid,psr | grep nginx
nginx: master process nginx    2854   0
nginx: worker process          4848   3
nginx: worker process          4849   0
grep --color=auto nginx        4859   1

在这里插入图片描述

worker_cpu_affinity

通过设置worker_cpu_affinity,将worker进程运行在指定cpu上,比如

worker_cpu_affinity 01 10;

在这里插入图片描述
01,启动第一个cpu内核;第一个worker进程(pid:3268)运行在第一个cpu内核。
10,启动第二个cpu内核。第二个worker进程(pid:3269)运行在第二个cpu内核。

再比如,

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

在这里插入图片描述
0001,代表第一个cpu内核;第一个worker进程(pid:3479)运行在第一个cpu内核上。
0010,代表第二个cpu内核;第二个worker进程(pid:3480)运行在第二个cpu内核上。
0100,代表第三个cpu内核;第三个worker进程(pid:3481)运行在第三个cpu内核上。
1000,代表第四个cpu内核;第四个worker进程(pid:3482)运行在第三个cpu内核上。

worker_priority

worker进程的优先级,即nice值。

[root@localhost ~]# ps axo pid,cmd,psr,nice | grep nginx
   3127 nginx: master process nginx   1   0
   3479 nginx: worker process         0   0
   3480 nginx: worker process         1   0
   3481 nginx: worker process         2   0
   3482 nginx: worker process         3   0
   3726 grep --color=auto nginx       1   0

我们来尝试修改下,

worker_priority 10;

在这里插入图片描述

worker_rlimit_nofile

worker_rlimt_nofile number,指定worker进程能够打开的文件数量的上限。

事件驱动相关配置
events{
}
worker_connections
events{
	worker_connections 10240;
}

worker_connections,每个worker进程所能打开的最大的并发连接数数量,比如10240
总最大并发数=worker_processes*worker_connections

use

use epoll,指明并发连接请求的处理方法,默认自动选择最优方法:epoll

accept_mutex

accept_mutex on|off;

  • on,由各个worker轮流处理请求。
  • off,每个新请求的到达都会通知(唤醒)所有的worker进程,但只有一个进程可获得连接,造成“惊群”,影响性能。
调试相关的指令
daemon

daemon on|off;,是否以守护进程方式运行nginx,默认是守护进程。直白点说就是,nginx是运行在前台还是后台。

master_process

master_process on|off,是否以master/worker模型运行nginx,默认是on。如果为off,则不启动worker进程。

error_log

error_log file [level],错误日志文件及级别,例如:

error_log  /var/log/nginx/error.log notice;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值