路漫漫其修远兮
吾将上下而求索

nginx学习:基础用法

Nginx简介

  engine X = Nginx

  Nginx是一款面向性能设计的HTTP服务器,相较于Apache、lighttpd具有占有内存少,稳定性高等优势。与旧版本(<=2.2)的Apache不同,nginx不采用每客户机一线程的设计模型,而是充分使用异步逻辑,削减了上下文调度开销,所以并发服务能力更强。整体采用模块化设计,有丰富的模块库和第三方模块库,配置灵活。 在Linux操作系统下,nginx使用epoll事件模型,得益于此,nginx在Linux操作系统下效率相当高。同时Nginx在OpenBSD或FreeBSD操作系统上采用类似于epoll的高效事件模型kqueue。

=================

http协议:

  URL:shceme://username:password@host:port/path;params?query#frag

http事务:

request:
  <method> <URL> <VERSION>
  HEADERS

  <body>

reponse:
  <VERSION> <STATUS> <REASON-PHRASE>
  HEADERS

  <body>

http请求方法:Method:GET/HEAD/POST, PUT/DELETE, TRACES, OPTIONS

http的状态码

Status Code:
1xx:
2xx:成功类响应码,200
3xx:重定向类的响应码,301, 302, 304
4xx:客户端错误,403,404
5xx:服务器端错误,502

http认证:

  基于ip认证

  基于用户认证 

httpd服务常用的工作模式:

prefork:进程模型,两级结构,主进程master负责生成子进程,每个子进程负责响应一个请求;
worker:线程模型,三级结构,主进程master负责生成子进程,每个子进程负责生成多个线程,每个线程响应一个请求;
event:主进程master负责生成子进程,每个子进程响应多个请求;

I/O模型:阻塞型、非阻塞型、复用型、信号驱动型、异步

同步/异步:关注消息通知机制;

消息通知:

同步:等待对方返回消息; 

异步:被调用者通过状态、通知或回调机制通知调用者被调用者的运行状态;

阻塞/非阻塞:关注调用者在等待结果返回之前所处的状态; 

  阻塞:blocking,调用结果返回之前,调用者被挂起;

  非阻塞:nonblocking,调用结果返回之前,调用者不会被挂起;

一次IO请求,都会由两阶段组成:

  第一步:等待数据,即数据从磁盘到内核内存; 

  第二步:复制数据,即数据内核内存到进程内存; 

复用型IO调用:

  select():1024

  poll():

event-driven:

  epoll(Linux):libevent

  Kqueue(BSD):

  Solaris:/dev/poll

============================

        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 powers several high-visibility sites, such as Netflix, Hulu, Pinterest, CloudFlare, Airbnb, WordPress.com, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard, MaxCDN and many others.

nginx说明

Nginx的程序架构:master/worker

一个master进程:

负责加载配置文件、管理worker进程、平滑升级

一个或多个worker进程

处理并响应用户请求

nginx也有缓存的功能,缓存相关的进程:

cache loader:载入缓存对象

cache manager:管理缓存对象

  特性:异步、事件驱动和非阻塞

    并发请求处理:通过kevent/epoll/select

    文件IO:高级IO

    sendfile(在内核中加载报文后直接封装报文响应,不用进入用户空间),异步,

    mmap(将用户空间内存映射成内核内存)

nginx高度模块块:高度模块化,但其模块早期不支持DSO机制;近期版本支持动态装载和卸载;

模块分类:

核心模块:core module

标准模块:

Standard HTTP modules:默认会被编译进去

Optional HTTP modules

Mail modules

Stream modules

3rd party modules

nginx的功用:

可以作为静态的web资源服务器;

可以作为结合FastCGI/uwSGI/SCGI等协议反代动态资源请求;

可以作为http/https协议的反向代理;

可以作为imap4/pop3协议的反向代理;

可以作为tcp/udp协议的反向代理;

nginx安装见其他博文

配置文件说明:

[root@localhost /usr/local/nginx/conf]#ls
conf.d                fastcgi_params.default  mime.types.default   uwsgi_params
fastcgi.conf          koi-utf                 nginx.conf           uwsgi_params.default
fastcgi.conf.default  koi-win                 scgi_params          win-utf
fastcgi_params        mime.types              scgi_params.default

配置文件的组成部分:

  主配置文件:nginx.conf

  include conf.d/*.conf #单独文件也可以

  fastcgi,uwsgi,scgi等协议相关的配置文件

  mime.types:支持的mime类型

主配置文件的配置指令:

  directive value [value2 …];

注意:

  (1) 指令必须以分号结尾;

  (2) 支持使用配置变量;

    内建变量:由Nginx模块引入,可直接引用;

    自定义变量:由用户使用set命令定义;

      set variable_name value;

      引用变量:$variable_name

主配置文件结构,也即全局配置段;

main block:主配置段,也即全局配置段;

event {
  ...
}  #事件驱动相关的配置;
http {
  ...
}  #http/https 协议相关的配置段;
stream {
  ...
} #流式协议配置段

http协议相关的配置结构

http {
    ...
    ...:各server的公共配置
    server {
        ...
    }	#每个server用于定义一个虚拟主机;
    server {
        ...
        server_name
        root
        alias
        location [OPERATOR] URL {
            ...
            if CONDITION {    #还可以使用条件判断
                ...
            }
        }
    }
}

main配置段常见的配置指令分类:

  正常运行必备的配置

  优化性能相关的配置

  用于调试及定位问题相关的配置

  事件驱动相关的配置

功能模块用法介绍

从下面开始,就一个模块一个模块的介绍使用方法和注意事项了,会比较枯燥,要有耐心

正常运行必备的配置:参考:http://nginx.org/en/docs/ngx_core_module.html

1、user #定义运行nginx进程的用户

Syntax:	user user [group];
Default:	user nobody nobody;
Context:	main	#只能用在main配置段
Defines user and group credentials used by worker processes. If group is omitted, a group whose name equals that of user is used.

2、pid /PATH/TO/PID_FILE;

指定存储nginx主进程进程号码的文件路径;
Context:	main	#只能用在main配置段

3、include file | mask;

指明包含进来的其它配置文件片断;
Context:	any	#通常放置在main配置段

Usage example:
include mime.types;
include vhosts/*.conf;

4、load_module file;

指明要装载的动态模块;
Context:	main	#只能用在main配置段

Example:
load_module modules/ngx_mail_module.so;  #是以nginx的安装目录为根目录进行寻找:/usr/local/nginx

性能优化相关的配置:

1、worker_processes number | auto;

worker进程的数量;通常应该为当前主机的cpu的物理核心数;
Syntax:	worker_processes number | auto;
Default:	
worker_processes 1;
Context:	main

2、worker_cpu_affinity cpumask …;

将nginx的每一个worker和cpu的每一个核心绑定在一起,因为nginx的一个worker可以处理很多的请求,

不一定worker数越多越好,如果有4个核心,则worker最好也是4个,这样是最高的效率,如果cpu4核但是worker5个,会增加进程切换时间,导致效率下降

Syntax:	worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main

CPU MASK:
00000001:0号CPU
00000010:1号CPU

测试:

[root@localhost ~]#shutdown -h 0    关机
修改虚拟机配置,将该虚拟机的cpu调整为4核心,开机

[root@localhost ~]#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

修改配置文件为4核心,

[root@localhost /usr/local/nginx/conf]#vim nginx.conf
worker_processes auto;
[root@localhost /etc/nginx]#nginx -t
[root@localhost /etc/nginx]#nginx -s reload  
[root@localhost /usr/local/nginx/conf]#ps aux | grep nginx #显示的是4个核心  
root       2648  0.0  0.7 109676  4856 ?        Ss   22:25   0:00 nginx: master process
nginx      2967  0.0  0.4 110056  3340 ?        S    22:26   0:00 nginx: worker process                                          
nginx      2968  0.0  0.4 110056  3340 ?        S    22:26   0:00 nginx: worker process                                          
nginx      2969  0.0  0.4 110056  3340 ?        S    22:26   0:00 nginx: worker process                                          
nginx      2970  0.0  0.4 110056  3340 ?        S    22:26   0:00 nginx: worker process

在192.168.175.12进行压测    

[root@localhost ~]#yi httpd-tools
[root@localhost ~]#ab -n 60000 -c 300 http://192.168.175.11/test.html
Server Software:        andy
Server Hostname:        192.168.175.11
Server Port:            80

Document Path:          /test.html
Document Length:        21 bytes

Concurrency Level:      300
Time taken for tests:   11.182 seconds	#使用了11秒
Complete requests:      60000

在192.168.175.11主机查看执行过程    

[root@localhost ~]#watch -n1 'ps axo pid,comm,psr | grep nginx'    
#worker_processes为auto看到nginx进程所在的核心在跳动,意思是在4个核心上切换,有的时候一个核心运行两个worker进程,但是2号核心没有进程在运行,不均衡。
[root@localhost ~]#ps axo pid,comm,psr | grep nginx
2917 nginx 3
2918 nginx 0
2919 nginx 0
2920 nginx 1
2921 nginx 3

修改配置文件绑定cpu核心数

[root@localhost /usr/local/nginx/conf]#vim nginx.conf 
worker_processes 4;
worker_cpu_affinity 00000001 00000010 00000100 00001000;
[root@localhost /usr/local/nginx/conf]#nginx -t
[root@localhost /usr/local/nginx/conf]#nginx -s reload 
[root@localhost /usr/local/nginx/conf]#ps axo pid,comm,psr | grep nginx    #可以看到每个核心绑定一个进程,非常好~
2917 nginx 3
4377 nginx 0
4378 nginx 1
4379 nginx 2
4380 nginx 3

压测,但是不给力,还是那样

[root@localhost ~]#ab -n 60000 -c 300 http://192.168.175.11/test.html
Server Software:        andy
Server Hostname:        192.168.175.11
Server Port:            80

Document Path:          /test.html
Document Length:        21 bytes

Concurrency Level:      300
Time taken for tests:   11.205 seconds	#差不多~(>_<)~
Complete requests:      60000

3、worker_priority number;

指定worker进程的nice值,设定worker进程优先级;[-20,20] 默认0,数字越小,优先级越高
Context:	main	#只能用在main配置段

4、worker_rlimit_nofile number;

worker进程所能够打开的文件数量上限;并发数量调高了,这个变量也要相应调高

调试、定位问题:

1、daemon on|off;

是否以守护进程方式运行Nignx;如果为了排错,可以前台运行nginx

2、master_process on|off;

Syntax:	master_process on | off;
Default:	
master_process on;
Context:	main
是否以master/worker模型运行nginx;默认为on;

3、error_log file [level];设定日志文件输出级别

Syntax:	error_log file [level];
Default:	
error_log logs/error.log error;
Context:	main, http, mail, stream, server, location
The second parameter determines the level of logging, and can be one of the following: debug, info, notice, warn, error, crit, alert, or emerg.

事件驱动相关的配置:

1、worker_connections number;

Syntax:	worker_connections number;
Default:	
worker_connections 512;
Context:	events

每个worker进程所能够打开的最大并发连接数数量;
worker_processes * worker_connections	#主机的最大的并发数

2、use method;

指明并发连接请求的处理方法;
use epoll;
Context:	events	#只能用在events配置段

3、accept_mutex on | off; #互斥锁,默认是off,最好设置为on

处理新的连接请求的方法;on意味着由各worker轮流处理新请求,Off意味着每个新请求的到达都会通知所有的worker进程;
Context:	events	#只能用在events配置段

http协议的相关配置:

http {
    ... ...
    server {
        ...
        server_name
        root
        location [OPERATOR] /uri/ {
            ...
        }
    }
    server {
        ...
    }
}

与套接字相关的配置:参考:http://nginx.org/en/docs/http/ngx_http_core_module.html

1、server { … }

配置一个虚拟主机;

server {
  listen address[:PORT]|PORT;	#好几种方式,都可以省略,具体看文档
  server_name SERVER_NAME;
  root /PATH/TO/DOCUMENT_ROOT;
}

2、listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE

  listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]

以下均可

listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

3、server_name name …; #只能放置在server中

指明虚拟主机的主机名称;后可跟多个由空白字符分隔的字符串;
支持*通配任意长度的任意字符;server_name *.andblog.cn
支持~起始的字符做正则表达式模式匹配;server_name ~^www\d+\.andyblog\.org$ #模式匹配,以www开头,后面跟多个数字,以org结尾的
匹配机制:1-4匹配到哪个就是哪个
  (1) 首先是字符串精确匹配;
  (2) 左侧*通配符;
  (3) 右侧*通配符;
  (4) 正则表达式;
比如:三个虚拟主机名:
  www.andblog.cn
  *.andblog.cn 
  ^www\d+\.andyblog\.org$
浏览器输入的是:www1.andblog.cn,按照上面的规则,应该匹配第二个

未经允许不得转载:江哥架构师笔记 » nginx学习:基础用法

分享到:更多 ()

评论 抢沙发

评论前必须登录!