Nginx从入门到掌握【(第1节(共3节)】

目录:

  1. Nginx简介.  

  2. Nginx的特性.

  3. Nginx的功能.

  4. Nginx的模块类型.

  5. 源码编译安装Nginx.

  6. nginx相关命令.

  7. Nginx的配置文件介绍.

  8. Nginx的配置指令详解.

 

正文:

一、Nginx简介:(摘自nginx官网wiki文档)

  NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. NGINX is known for its high performance, stability(稳定性), rich feature set, simple configuration, and low resource consumption(消耗).

  NGINX is one of a handful of servers written to address the C10K problem. Unlike traditional servers, NGINX doesn’t rely(依靠) on threads to handle (线程处理)requests. Instead it uses a much more scalable(可扩展的) event-driven (asynchronous,异步) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from NGINX’s high-performance and small memory footprint. NGINX scales(规模) in all directions: from the smallest VPS all the way up to large clusters of servers.

 

二、Nginx的特性. 

  1)模块化设计;

  2)高可靠性:

    master --> worker 

  3)低内存消耗: 

    10000个keep-alive模式下的connection,仅需要2.5MB的内存; 

  4)支持热部署:

    不停机而更新配置文件,日志文件滚动,升级程序版本; 

 

三、Nginx的功能. 

  1.基本功能:
    1)静态资源的web服务器,能缓存打开的文件描述符;
    2)http,smpt,pop3协议的反向代理服务器;
    3)缓存加速,负载均衡;
    4)支持FastCGI(fpm,LNMP),uWSGI(python)等; 
    5)模块化(非DSO机制),过滤器zip,SSI及图像的大小写调整;
    6)支持SSL:
  2.扩展功能:
    1)基于名称和IP的虚拟主机;
    2)支持keepalive;
    3)支持平滑升级;
    4)定制访问日志,支持使用日志缓冲区提供日志存储性能;
    5)支持url rewrite;
    6)支持路径别名;
    7)支持基于IP及用户的访问限制;
    8)支持速率限制,支持并发数限制;

 

四、Nginx的模块类型.

  1. 核心模块
  2. Standard HTTP modules 
  3. Optional HTTP modules  
  4. Mail modules 
  5. 3rd party modules 

 

五、源码编译安装Nginx. 

  系统环境:CentOS7.3 

  nginx软件包版本:1.10.2 Stable version

  Nginx的安装方式有两种,即RPM安装和源码编译安装。此处采用编译安装的方式,Linux系统为CentOS7.3. 

  首先到官网下载相应Stable version安装包:

1

2

3

[root@nginx tools]# cat /etc/redhat-release 

CentOS Linux release 7.3.1611 (Core) 

[root@nginx tools]# wget http://nginx.org/download/nginx-1.10.2.tar.gz

  然后开始安装: 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

[root@nginx ~]# useradd -s /sbin/nologin -M nginx

//创建nginx用户及nginx组来运行nginx服务进程.

[root@nginx ~]# mkdir /data/nginx/logs/ -p

[root@nginx ~]# touch /data/nginx/logs/error.log  

[root@nginx ~]# mkdir /data/nginx -p

[root@nginx ~]# touch /data/nginx/{nginx.pid,nginx.lock}  

//创建相关文件的存储位置.

[root@nginx ~]# cd /mnt/tools/

[root@nginx tools]# yum -y gd gd-devel pcre pcre-devel

[root@nginx tools]# tar zxf nginx-1.10.2.tar.gz

[root@nginx tools]# cd nginx-1.10.2

[root@nginx nginx-1.10.2]# ls

auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src

[root@nginx nginx-1.10.2]#

  注:

  1)gd库,是php处理图形的扩展库,GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片。 

  2)PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括 perl 兼容的正则表达式库。

  查看编译安装的选项:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

[root@nginx nginx-1.10.2]# ./configure --help

 

  --help                             print this message

 

  --prefix=PATH                      set installation prefix

  --sbin-path=PATH                   set nginx binary pathname

  --modules-path=PATH                set modules path

  --conf-path=PATH                   set nginx.conf pathname

  --error-log-path=PATH              set error log pathname

  --pid-path=PATH                    set nginx.pid pathname

  --lock-path=PATH                   set nginx.lock pathname

 

  --user=USER                        set non-privileged user for

                                     worker processes

  --group=GROUP                      set non-privileged group for

                                     worker processes

 

  --build=NAME                       set build name

  --builddir=DIR                     set build directory

 

  --with-select_module               enable select module

  --without-select_module            disable select module

  --with-poll_module                 enable poll module

  --without-poll_module              disable poll module

 

  --with-threads                     enable thread pool support

 

  --with-file-aio                    enable file AIO support

  --with-ipv6                        enable IPv6 support

 

  --with-http_ssl_module             enable ngx_http_ssl_module

  --with-http_v2_module              enable ngx_http_v2_module

  --with-http_realip_module          enable ngx_http_realip_module

  --with-http_addition_module        enable ngx_http_addition_module

  --with-http_xslt_module            enable ngx_http_xslt_module

  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module

  --with-http_image_filter_module    enable ngx_http_image_filter_module

  --with-http_image_filter_module=dynamic

   

  ......

 

[root@nginx nginx-1.10.2]#

  注:以上模块编译时需要有选择性的安装,万一哪个模块安装时漏掉了也不用担心,因为nginx支持热部署,可以随时增加需要的模块!

  下一步进行编译:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

[root@nginx nginx-1.10.2]# ./configure \ 

--prefix=/usr/local/nginx-1.10.2 \ 

--error-log-path=/data/nginx/logs/error.log \ 

--pid-path=/data/nginx/nginx.pid \ 

--lock-path=/data/nginx/nginx.lock \ 

--user=nginx \

--group=nginx \

--with-threads \

--with-http_ssl_module \ 

--with-http_image_filter_module \

--with-http_image_filter_module=dynamic \

--with-http_flv_module \             

--with-http_mp4_module  \           

--with-http_gunzip_module \          

--with-http_gzip_static_module \ 

--with-http_slice_module  \

--with-stream \                  

[root@nginx nginx-1.10.2]# echo $?

0

[root@nginx nginx-1.10.2]# make && make install

[root@nginx nginx-1.10.2]# echo $?

0

 做软连接: 

1

2

3

4

5

6

[root@nginx nginx-1.10.2]# cd

[root@nginx ~]# ls /usr/local/nginx-1.10.2/ -d

/usr/local/nginx-1.10.2/

[root@nginx ~]# ln -sv /usr/local/nginx-1.10.2/ /usr/local/nginx

"/usr/local/nginx" -> "/usr/local/nginx-1.10.2/"

[root@nginx ~]#

 启动服务并查看监听端口:

1

2

3

4

[root@nginx ~]# /usr/local/nginx/sbin/nginx 

[root@nginx ~]# ss -tunlp |egrep "nginx"

tcp    LISTEN     0      128       *:80                    *:*                   users:(("nginx",pid=11743,fd=6),("nginx",pid=11742,fd=6))

[root@nginx ~]#

 提前关闭防火墙. 

1

2

3

4

5

6

7

8

[root@nginx ~]# systemctl list-unit-files |grep firewalld

firewalld.service                           enabled 

[root@nginx ~]# systemctl disable firewalld.service

Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.

Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.

[root@nginx ~]# systemctl list-unit-files |grep firewalld

firewalld.service                           disabled

[root@nginx ~]#

 浏览器访问测试:

wKiom1h0oqLAKGAMAAB2xkkyfoY063.png

 

六、nginx相关命令. 

 1. 开启nginx服务的初始命令:

  # /usr/local/nginx/sbin/nginx 

  注:该命令自己也可以写成脚本,通过systemctl(CentOS7)或service(CentOS6)启动. 

 2. 新改的配置生效方式 

  # /usr/local/nginx/sbin/nginx -s SIGNAL 

  SIGNAL包括: reload, stop, quit, reopen 
 3. 查看系统已装载的nginx模块选项:

  # /usr/local/nginx/sbin/nginx -V         

 

七、Nginx的配置文件介绍. 

 Nginx的配置段主要有以下三项:

  1、main配置段:全局配置段              
  2、event: 定义event模型工作特性        
  3、http{}: 定义http协议相关的配置    

 配置文件介绍:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf

  

#user  nobody;  //定义Nginx进程运行的用户和用户组

worker_processes  1;  //nginx进程数,建议设置为物理CPU总核心减1个。

 

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;  //定义全局日志类型

 

#pid        logs/nginx.pid;  //保存nginx进程的pid文件

 

 

events {

    worker_connections  1024;  //单个进程最大连接数(最大连接数=连接数*进程数)

     

}

 

 

http {

    include       mime.types;  //文件扩展名与文件类型映射表.

    default_type  application/octet-stream;  //默认文件类型

http://blog.51cto.com/user_index.php?action=addblog_new&did=304899

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

    #                  '$status $body_bytes_sent "$http_referer" '

    #                  '"$http_user_agent" "$http_x_forwarded_for"';

 

    #access_log  logs/access.log  main;

 

    sendfile        on;

    #tcp_nopush     on;

 

    #keepalive_timeout  0;

    keepalive_timeout  65;  //长连接超时时间,单位是秒

 

    gzip  on;  //开启gzip压缩输出

     

     

    server {  //虚拟主机的配置

        listen       80;

        server_name  localhost;  //域名可以有多个,用空格隔开

 

        #charset koi8-r;

 

        #access_log  logs/host.access.log  main;

 

        location / {

            root   html;

            index  index.html index.htm;

        }

 

        #error_page  404              /404.html;

 

        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }

 

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

        #

        #location ~ \.php$ {

        #    proxy_pass   http://127.0.0.1;

        #}

 

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        #

        #location ~ \.php$ {

        #    root           html;

        #    fastcgi_pass   127.0.0.1:9000;

        #    fastcgi_index  index.php;

        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

        #    include        fastcgi_params;

        #}

 

        # deny access to .htaccess files, if Apache's document root

        # concurs with nginx's one

        #

        #location ~ /\.ht {

        #    deny  all;

        #}

    }

 

 

    # another virtual host using mix of IP-, name-, and port-based configuration

    #

    #server {

    #    listen       8000;

    #    listen       somename:8080;

    #    server_name  somename  alias  another.alias;

 

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

 

 

    # HTTPS server  //https配置段.

    #

    #server {

    #    listen       443 ssl;

    #    server_name  localhost;

 

    #    ssl_certificate      cert.pem;

    #    ssl_certificate_key  cert.key;

 

    #    ssl_session_cache    shared:SSL:1m;

    #    ssl_session_timeout  5m;

 

    #    ssl_ciphers  HIGH:!aNULL:!MD5;

    #    ssl_prefer_server_ciphers  on;

 

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

 

}

 

八、Nginx的配置指令详解. 

 1. 正常运行的必备配置段:

 1) user USERNAME [GROUPNAME]  

   指定运行worker进程的用户和组;
   例:user nginx nginx  

   注: 用户和组如果一起部署且相同的话,GROUPNAME可以省略. 

 2) pid /path/to/PID_FILE 

   指定nginx守护进程的pid文件. 

   例: pid /data/nginx/nginx.pid  

   注: pid文件的作用在于防止进程启动多个副本.只有获得pid文件写入权限的进程才能正常启动并  把自身进程pid写入该文件中,其他同一个程序的多余进程会自动退出.

  查看本系统的pid文件:

1

2

3

4

5

6

7

8

9

10

11

[root@nginx ~]# cat /data/nginx/nginx.pid

cat/data/nginx/nginx.pid: 没有那个文件或目录

[root@nginx ~]# /usr/local/nginx/sbin/nginx 

[root@nginx ~]# cat /data/nginx/nginx.pid

2561

[root@nginx ~]# ps -aux |egrep "nginx"

root       2529  0.1  0.5 151800  5436 pts/0    S+   10:18   0:00 vim /usr/local/nginx/conf/nginx.conf

root       2561  0.0  0.1  45376  1112 ?        Ss   10:27   0:00 nginx: master process /usr/local/nginx/sbin/nginx

nginx      2562  0.0  0.1  45824  1884 ?        S    10:27   0:00 nginx: worker process

root       2565  0.0  0.0 112664   972 pts/1    S+   10:28   0:00 grep -E --color=auto nginx

[root@nginx ~]#

 3) worker_connections  NUM; 

   指定所有worker进程所能够打开的最大文件句柄数; 
   默认打开文件最大数为1024个.

 2. 性能优化相关的配置:

 1) worker_processes NUM; 

   指定nginx进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计为8)。

   例: worker_processes 4;

 2) worker_cpu_affinity cpumask ...; 
   指定为每个进程分配CPU,提升缓存的命中率.

   例: worker_cpu_affinity 00000001 00000010 00000100 00001000;

   上例中将4个进程分配到4个cpu,注意与worker_process数相对应.当然可以写多个,或者将一个进程分配到多个cpu。

 3) timer_resolution TIME; 

   指定计时器解析度:降低此值,可减少gettimeofday()系统调用的次数;

   默认值:none
   例: timer_resolution 100ms;

   该配置指令允许用户减少调用gettimeofday()的次数。默认情况下,该函数在每次I/O端口监听 (比如epoll_wait)返回后都将被调用,而通过timer_resolution配置选项可以直接指定调用 gettimeofday()函数的间隔时间.

 4) worker_priority NUM:  

   指明worker进程的nice值,即worker进程的优先级; 

   nice值越小,优先级越高,默认只能由管理员有权限调整nice值; 

 3. 事件相关的配置: 

 1) accept_mutex {off|on};
   指定master进程调度用户请求至各worker进程时使用的负载均衡锁; on表示能让多个worker轮流地、序列化地去响应新请求;
 2) lock_file file;
   accept_mutex用到的锁文件路径;     
 3) use [epoll|rtsig|select|poll]; 
   指明使用的时间模型;建议让nginx自行选择;     
 4) worker_connections #; 
   设定单个worker进程所能够处理的最大并发连接数量;
   计算公式:worker_connections * work_processes , 可能会小于这个值; 

 4. 用户用于调试, 定位问题:
 1) daemon {on|off}; 
   是否以守护进程方式运行nginx: 调试时应该设置为off。 
 2) master_process {on|off}; 
   是否以master/worker模型来运行nginx;调试时可以设置为off;
 3) error_log file |stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg]; 
   语法: error_log [位置] [级别]; 
   若要使用debug级别, 需要在编译nginx时使用--with-debug选项; 

 5. 总结:常需要进行调整的参数:
   worker_processes,worker_connections,worker_cpu_affinity,worker_priority. 

 

--- 第一部分完成!

 

 

本文转自 羽丰1995 51CTO博客,原文链接:http://blog.51cto.com/13683137989/1891105

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值