首页 > 技术文章 > nginx-编译安装 第一章

zy09 2019-01-04 19:08 原文

nginx 第一章:编译安装

 

 nginx 官网网站:http://nginx.org/en/   

1.基础说明

基本HTTP服务器功能
其他HTTP服务器功能
邮件代理服务器功能
TCP/UDP代理服务器功能
体系结构和可伸缩性
经测试的操作系统和平台

 

nginx [engine x]是一个HTTP和反向代理服务器,一个邮件代理服务器和一个通用的TCP / UDP代理服务器,最初由Igor Sysoev编写。很长一段时间,它一直在许多负载很重的俄罗斯网站上运行,包括 Yandex, Mail.Ru, VK和 Rambler。据Netcraft称,nginx 在2018年12月服务或代理了 25.89%最繁忙的网站。以下是一些成功案例: Dropbox, Netflix, Wordpress.com, FastMail.FM。

 

1.基本的HTTP服务器功能


提供静态和 索引 文件, 自动索引 ; 打开文件描述符缓存 ;
通过缓存加速反向代理 ; 负载均衡和容错 ;
通过缓存FastCGI, uwsgi, SCGI和 memcached 服务器加速支持 ; 负载均衡和容错 ;
模块化架构。过滤器包括 gzipping,字节范围,分块响应, XSLT, SSI和图像变换过滤器。如果由代理或FastCGI / uwsgi / SCGI服务器处理,则可以并行处理单个页面中的多个SSI包含;
SSL和TLS SNI支持 ;
支持HTTP / 2, 具有加权和基于依赖性的优先级。


2.其他HTTP服务器功能
基于名称和基于IP的 虚拟服务器 ;
保持活跃 和流水线连接支持;
访问日志格式, 缓冲日志写入, 快速日志轮换和 syslog日志记录 ;
3xx-5xx错误代码 重定向 ;
重写模块: 使用正则表达式更改URI ;
根据 客户端地址执行不同的功能 ;
基于客户端IP地址, 密码(HTTP基本身份验证)和 子请求结果的访问控制 ;
验证 HTTP referer ;
该PUT,DELETE,MKCOL,复制和移动方法;
FLV 和 MP4 流媒体;
响应速度限制 ;
限制 来自一个地址的同时连接 或 请求的数量 ;
基于IP的地理定位 ;
A / B测试 ;
请求镜像 ;
嵌入式Perl ;
njs脚本语言。

3.邮件代理服务器功能

用户 使用外部HTTP 身份验证 服务器重定向到 IMAP 或 POP3服务器;

使用外部HTTP 身份验证 服务器进行用户身份 验证,并将连接重定向到内部 SMTP服务器;
验证方法:
POP3:USER / PASS,APOP,AUTH LOGIN / PLAIN / CRAM-MD5;
IMAP:登录,AUTH LOGIN / PLAIN / CRAM-MD5;
SMTP:AUTH LOGIN / PLAIN / CRAM-MD5;

SSL支持;
STARTTLS和STLS支持。


4.TCP / UDP代理服务器功能
TCP和UDP的通用代理 ;
SSL和TLS SNI支持TCP;

负载均衡和容错 ;
基于客户端地址的访问控制 ;
根据客户端地址执行不同的功能 ;
限制 来自一个地址的同时连接数 ;
访问日志格式, 缓冲日志写入, 快速日志轮换和 syslog日志记录 ;
基于IP的地理定位 ;
A / B测试 ;
njs脚本语言。

5.架构和可扩展性
一个主要和几个工人流程; 工作进程在非特权用户下运行;
配置灵活 ;
在不中断客户端服务的情况下重新配置 和升级可执行文件 ;
支持 kqueue(FreeBSD 4.1+),epoll(Linux 2.6+),/ dev / poll(Solaris 7 11/99 +),事件端口(Solaris 10),select和poll;
支持各种kqueue功能,包括EV_CLEAR,EV_DISABLE(暂时禁用事件),NOTE_LOWAT,EV_EOF,可用数据的数量,错误代码;
支持各种epoll功能,包括EPOLLRDHUP(Linux 2.6.17 +,glibc 2.8+)和EPOLLEXCLUSIVE(Linux 4.5 +,glibc 2.24+);
sendfile(FreeBSD 3.1 +,Linux 2.2 +,macOS 10.5+),sendfile64(Linux 2.4.21+)和sendfilev(Solaris 8 7/01 +)支持;
文件AIO (FreeBSD 4.3 +,Linux 2.6.22+);
DIRECTIO (FreeBSD 4.4 +,Linux 2.4 +,Solaris 2.6 +,macOS);
Accept-filters(FreeBSD 4.1 +,NetBSD 5.0+)和TCP_DEFER_ACCEPT(Linux 2.4+) 支持 ;
10,000个非活动HTTP保持活动连接占用大约2.5M内存;
数据复制操作保持在最低限度。

6.经测试的操作系统和平台
FreeBSD 3 - 11 / i386; FreeBSD 5 - 11 / amd64;
Linux 2.2 - 4 / i386; Linux 2.6 - 4 / amd64; Linux 3 - 4 / armv6l,armv7l,aarch64,ppc64le;
Solaris 9 / i386,sun4u; Solaris 10 / i386,amd64,sun4v;
AIX 7.1 / powerpc;
HP-UX 11.31 / ia64;
macOS / ppc,i386;
Windows XP,Windows Server 2003。

二.安装

1、环境准备:先安装准备环境

yum install gcc gcc-c++ automake pcre pcre-devel zlip zlib-devel openssl openssl-devel 

gcc为GNU Compiler Collection的缩写,可以编译C和C++源代码等,它是GNU开发的C和C++以及其他很多种语言 的编译器(最早的时候只能编译C,后来很快进化成一个编译多种语言的集合,如Fortran、Pascal、Objective-C、Java、Ada、 Go等。)
gcc 在编译C++源代码的阶段,只能编译 C++ 源文件,而不能自动和 C++ 程序使用的库链接(编译过程分为编译、链接两个阶段,注意不要和可执行文件这个概念搞混,相对可执行文件来说有三个重要的概念:编译(compile)、链接(link)、加载(load)。
  源程序文件被编译成目标文件,多个目标文件连同库被链接成一个最终的可执行文件,可执行文件被加载到内存中运行)。因此,通常使用 g++ 命令来完成 C++ 程序的编译和连接,该程序会自动调用 gcc 实现编译。 gcc-c++也能编译C源代码,只不过把会把它当成C++源代码,后缀为.c的,gcc把它当作是C程序,而g++当作是c++程序;后缀为.cpp的,两者都会认为是c++程序,注意,虽然c++是c的超集,但是两者对语法的要求是有区别的。 automake是一个从Makefile.am文件自动生成Makefile.in的工具。为了生成Makefile.in,automake还需用到perl,由于automake创建的发布完全遵循GNU标准,所以在创建中不需要perl。libtool是一款方便生成各种程序库的工具。 pcre pcre-devel:在Nginx编译需要 PCRE(Perl Compatible Regular Expression),因为Nginx 的Rewrite模块和HTTP 核心模块会使用到PCRE正则表达式语法。 zlip zlib-devel:nginx启用压缩功能的时候,需要此模块的支持。 openssl openssl-devel:开启SSL的时候需要此模块的支持。

 安装pcre 和zlib

wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.42.tar.gz
tar xvf pcre-8.42.tar.gz 
cd pcre-8.42
./configure
make
make install

wget https://jaist.dl.sourceforge.net/project/libpng/zlib/1.2.11/zlib-1.2.11.tar.gz
tar -zxvf zlib-1.2.11.tar.gz 
cd zlib-1.2.11
./configure
make
make install

 

 2、下载nginx 安装包:  官网地址:http://nginx.org/

  截止当前最新稳定版本为 nginx-1.14.2,在Linux 下使用 wget 进行下载:

[root@localhost sbin]# cd /usr/local/src/
[root@localhost src]# ls
[root@localhost src]#  wget http://120.52.51.15/nginx.org/download/nginx-1.14.2.tar.gz
--2019-01-04 04:33:01--  http://120.52.51.15/nginx.org/download/nginx-1.14.2.tar.gz
Connecting to 120.52.51.15:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1015384 (992K) [application/octet-stream]
Saving to: ‘nginx-1.14.2.tar.gz’

100%[=================================================>] 1,015,384   --.-K/s   in 0.1s    

2019-01-04 04:33:01 (7.43 MB/s) - ‘nginx-1.14.2.tar.gz’ saved [1015384/1015384]

3.解压安装包

[root@localhost src]# 
[root@localhost src]# 
[root@localhost src]# tar xvf nginx-1.14.2.tar.gz ^C
[root@localhost src]# cd nginx-1.14.2
[root@localhost nginx-1.14.2]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@localhost nginx-1.14.2]# pwd
/usr/local/src/nginx-1.14.2
[root@localhost nginx-1.14.2]# 

4.开始编译安装

[root@localhost nginx-1.14.2]# ./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 --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre=/usr/local/src/pcre-8.42 --with-zlib=/usr/local/src/zlib-1.2.11
[root@localhost nginx-1.14.2]# make
[root@localhost nginx-1.14.2]# make install

备注:nginx完成安装以后,有四个主要的目录:

conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。
html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。
sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

5.通过命令启动和关闭nginx:

[root@localhost sbin]# ./nginx 
nginx: [emerg] getpwnam("nginx") failed
[root@localhost sbin]# useradd -s /s
sbin/ srv/  sys/  
[root@localhost sbin]# useradd -s /sbin/nologin -M nginx
[root@localhost sbin]# id nginx
uid=1000(nginx) gid=1000(nginx) groups=1000(nginx)
[root@localhost sbin]# ls
nginx
[root@localhost sbin]# ./nginx
[root@localhost sbin]# ss -tnl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128               *:80                            *:*                  
LISTEN      0      128               *:22                            *:*                  
LISTEN      0      100       127.0.0.1:25                            *:*                  
LISTEN      0      128              :::22                           :::*                  
LISTEN      0      100             ::1:25                           :::*                  
[root@localhost sbin]# 

6.重新读取配置文件和关闭服务:

/usr/local/nginx/sbin/nginx/nginx  #启动 服务
/usr/local/nginx/sbin/nginx/nginx   -s  reload  #不停止服务重读配置文件
/usr/local/nginx/sbin/nginx/nginx -s stop #停止服务  #停止服务

7.验证端口是否开启:

[root@localhost sbin]# 
[root@localhost sbin]# ps -ef |grep nginx
root      1314     1  0 05:10 ?        00:00:00 nginx: master process ./nginx   # nginx 主进程只有一个
nginx     1315  1314  0 05:10 ?        00:00:00 nginx: worker process      #nginx  工作进程,可以通过配置文件修改
root      1319 21710  0 05:13 pts/1    00:00:00 grep --color=auto nginx
[root@localhost sbin]# ss -tnl              #查看开启的监听端口
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128               *:80                            *:*                  
LISTEN      0      128               *:22                            *:*                  
LISTEN      0      100       127.0.0.1:25                            *:*                  
LISTEN      0      128              :::22                           :::*                  
LISTEN      0      100             ::1:25                           :::*                  
[root@localhost sbin]# lsof -i:80            #查看 80 端口绑定的应用程序
COMMAND  PID  USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
nginx   1314  root    6u  IPv4 27941366      0t0  TCP *:http (LISTEN)
nginx   1315 nginx    6u  IPv4 27941366      0t0  TCP *:http (LISTEN)
[root@localhost sbin]# 

支持的信号:

kill  -QUIT 13337  #平缓关闭Nginx,即不再接受新的请求,但是等当前请求处理完毕后再关闭Nginx。
kill  -TERM  21665 #快速停止Nginx服务
kill  -HUP 21703 #使用新的配置文件启动进程然后平缓停止原有的nginx进程,即平滑重启。 
kill -USR1 21703   #重新打开配置文件,用于nginx 日志切割
日志切割的脚本:
---------------------------------------------------------------------------------------
#!/bin/bash
PID=`cat /var/run/nginx/nginx.pid`
mv   /var/log/nginx/error.log   /var/log/nginx/`date  +%Y_%m_%d:%H:%M:%S`.error.log
mv   /var/log/nginx/access.log   /var/log/nginx/`date  +%Y_%m_%d:%H:%M:%S`.access.log
kill -USR1 $PID
---------------------------------------------------------------------------------------

[root@localhost sbin]# chmod 755 log_cutting.sh 
[root@localhost sbin]# ./log_cutting.sh 
[root@localhost sbin]# ls
log_cutting.sh  nginx
[root@localhost sbin]# cd /var/log/nginx/
[root@localhost nginx]# ls
2019_01_04:05:44:39.access.log  2019_01_04:05:44:39.error.log  access.log  error.log

三:nginx 主配置文件:nginx.conf

3.1:默认配置:配置文件默认保存在path/conf当中,默认的配置文件为nginx.conf,以下是编译安装后的默认配置:

[root@localhost conf]# cat nginx.conf
#全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,nginx PID 路径,日志路径等。
#user  nobody;
worker_processes  1;   #默认启动一个工作进程

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {    #events模块,主要影响nginx服务器与用户网络连接,比如是够允许同时接受多个网络连接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络连接进行序列化等。
    worker_connections  1024;   #设置单个工作进程可以接受的最大并发数
}


http {         #http模块是nginx 服务器配置中的重要部分,缓存,代理,和日志格式定义等绝大多数功能和第三方模块都可以在这设置,http 快可以包含多个server块,而一个server 快中又可以包含多个location 块,server 块可以配置文件引入,MIME-Type 定义,日志自定义,是否用sendfile 连接超时时间和单个连接的请求上限等.
    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;

    sendfile        on;      #是否调用sendfile 函数(zero copy --> 零 copy方式)来输出文件,普通应用打开,可以大幅度提升nginx 的读文件性能,如果文件是下载就需要关闭,
    #tcp_nopush     on;

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

    #gzip  on;    

    server {   #设置一个虚拟主机,可以包含自己的全局块,同时也包含多个 locating 模块,比如本虚拟机监听的端口,本虚拟机的名称和ip 配置,多个server  可以使用一个端口,必须都使用80 端口提供web 服务.
        listen       80;   #server 全局配置,配置监听的端口
        server_name  localhost;  #本server 名称,当访问此名称的时候nginx 会调用当前server 内部的配置程序进行匹配.

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {    #location 其实是server的一个指令,为nginx 服务器提供比较多而且灵活的指令,都在location 中体现的,主要基于nginx 接收到的请求字符串,并对用户的请求URI进行匹配,并对特定的指令进行处理,包括地址重定向,数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的配置也是在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 {    #location 处理对应的不同错误代码的页面定义到/50x.html ,这个跟对应其server 中定义的目录下,
            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
    #
    #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;
    #    }
    #}

}

 

 

 3.2:配置nginx 主进程的启动用户和工作进程数:

user  xxxx;   #每一条指令都要以分号结尾
worker_processes  1; #可以指定启动的固定nginx进程数,或使用auto,auto是启动与当前CPU 线程相同的进程数,如CPU是四核八线程的就启动八个进程的Nginx工作进程。

3.3:绑定Nginx 工作进程到不同的CPU上:

  默认Nginx是不进行保定的,绑定并不能是当前nginx进程独占以一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx 工作进程在不同cpu上的跳转,减少了CPU对进程的资源分配与回收,因此可以有效的提升nginx服务器的性能,配置如下:

复制代码
[root@Server1 nginx]# grep process /proc/cpuinfo  | wc -l #确认CPU的核心数量
4
四个线程CPU的配置:
worker_processes  4; 
worker_cpu_affinity 0001 0010 0100 1000;

八个线程CPU的配置:
worker_processes  8; 
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
复制代码

3.4:PID和错误日志文件路径:

复制代码
#pid        logs/nginx.pid;   #可以指定绝对路径
#error_log  logs/error.log;  #指定错误日志路径
#error_log  logs/error.log  notice;  #指定一个日志记录级别
#error_log  logs/error.log  info;

支持的日志级别:
语法:
error_log file [ debug | info | notice | warn | error | crit ]  | [{  debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_mail | debug_mysql } ]
日志级别 = 错误日志级别 | 调试日志级别; 或者
日志级别 = 错误日志级别;
错误日志的级别: emerg, alert, crit, error, warn, notic, info, debug, 
调试日志的级别: debug_core, debug_alloc, debug_mutex, debug_event, debug_http, debug_mail, debug_mysql

error_log 指令的日志级别配置分为错误日志级别和调试日志级别,错误日志只能设置一个级别,而且错误日志必须书写在调试日志级别的前面,另外调试日志可以设置多个级别,其他配置方法可能无法满足需求。
复制代码

 3.5:配置文件的引入:include

复制代码
#include 能够优化nginx.cnf 配置文件,使得配置文件条理有序
include file; #file是要导入的文件,支持相对路径,一般在html目录里面 导入一个conf文件,并配置不同主机名的页面,编辑nginx.conf主配置文件: include /usr/local/nginx/conf.d/samsung.conf; #在最后一个大括号里面加入一项,*是导入任何以conf结尾的配置文件 在/usr/local/nginx/conf.d/创建一个test.conf,内容如下: [root@Server1 nginx]# grep -v "#" conf.d/test.conf | grep -v "^$" server { listen 8080; server_name test.china.cn; location / { root html; index index1.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }

http {    #include  命令添加在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;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

include /usr/local/nginx/nginx.d/test.conf;
#gzip on;

复制代码

 

推荐阅读