nginx入门

nginx特点

占用cpu/内存资源少,相对apache并发处理能力强;nginx采用epoll事件响应模式,apache使用遍历select模式。

nginx安装

yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

安装pcre? nginx要在rewrite时要解析正则表达式,PCRE是正则解析库

//下载tar包

wget http://nginx.org/download/nginx-1.13.7.tar.gz

tar -xvf nginx-1.13.7.tar.gz

抹去nginx的版本,该步非必需;有时我们打开一个网站的时候会显示404,后面跟一个nginx1.7之类的信息,去掉后外部就看不到nginx的版本了,安全

[root@phoenix nginx-1.13.7]# cat src/core/nginx.h 

#define nginx_version      1013007
#define NGINX_VERSION      "1.13.7"
#define NGINX_VER          "nginx/" NGINX_VERSION

#define NGINX_VAR          "NGINX"
#define NGX_OLDPID_EXT     ".oldbin"

[root@phoenix nginx-1.13.7]# sed -i -e 's/1.13.7//g' -e 's/nginx//WS/g' -e 's/"NGINX"/"WS"/g' src/core/nginx.h
[root@phoenix nginx-1.13.7]# 
[root@phoenix nginx-1.13.7]# cat src/core/nginx.h 

#define nginx_version      1013007
#define NGINX_VERSION      ""
#define NGINX_VER          "WS" NGINX_VERSION

#ifdef NGX_BUILD
#define NGINX_VER_BUILD    NGINX_VER " (" NGX_BUILD ")"
#else
#define NGINX_VER_BUILD    NGINX_VER
#endif

#define NGINX_VAR          "WS"
#define NGX_OLDPID_EXT     ".oldbin"

 创建用户,用于nginx启动,该步非必须,省略用户与组的指定时,默认使用root用户,也可以直接指定root用户

[root@phoenix nginx-1.13.7]# useradd black
[root@phoenix nginx-1.13.7]# id black
uid=1002(black) gid=1002(black) groups=1002(black)

cd nginx-1.13.7
./configure --prefix=/usr/local/nginx --user=black --group=black --with-http_stub_status_module --with-http_ssl_module

配置的时候可以指定目录,不指定的话,配置结束时给出了默认配置的目录

Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

make
make install

安装过程无报错,即安装成功

关于状态的监控

1 编译nginx,加上参数 --with-http_stub_status_module

以我自己的编译选项为例:

  #配置指令
  ./configure --prefix=/usr/local
    --user=nginx 
    --group=nginx
    --with-http_ssl_module
    --with-http_realip_module
    --http-client-body-temp-path=/usr/local/var/tmp/nginx/client 
    --http-proxy-temp-path=/usr/local/var/tmp/nginx/proxy 
    --http-fastcgi-temp-path=/usr/local/var/tmp/nginx/fcgi 
    --http-scgi-temp-path=/usr/local/var/tmp/nginx/scgi 
    --http-uwsgi-temp-path=/usr/local/var/tmp/nginx/uwsgi 
    --with-http_geoip_module 
    --with-http_stub_status_module
2 修改nginx配置文件,添加监控状态配置

在nginx.conf的server块中添加如下代码

location /nginx_status {
    # Turn on nginx stats
    stub_status on;
    # I do not need logs for stats
    access_log   off;
    # Security: Only allow access from 192.168.1.100 IP #
    #allow 192.168.1.100;
    # Send rest of the world to /dev/null #
    #deny all;
}
这段代码是加在默认的server里的,
假设默认server的配置为

listen       127.0.0.1:80;
server_name  127.0.0.1;
那么访问nginx的状态,就可以通过 curl 127.0.0.1/nginx_status访问了

返回结果类似于:

Active connections: 1 
server accepts handled requests
 655 655 1985 
Reading: 0 Writing: 1 Waiting: 0 

添加环境变量

export PATH=/usr/local/nginx/sbin:$PATH

常用命令

版本查看,显示WS是因为之前抹除了nginx的版本

[root@phoenix nginx-1.13.7]# nginx -V
nginx version: WS
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=black --group=black --with-http_stub_status_module --with-http_ssl_module

配置文件检测

[root@phoenix nginx-1.13.7]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

nginx启动

[root@phoenix nginx-1.13.7]# netstat -tunlp |grep 80
[root@phoenix nginx-1.13.7]# nginx
[root@phoenix nginx-1.13.7]# netstat -tunlp |grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      4178/nginx: master 

 一个master和一个worker进程

[root@phoenix nginx-1.13.7]# ps -ef |grep nginx
root      4178     1  0 19:26 ?        00:00:00 nginx: master process nginx
black     4179  4178  0 19:26 ?        00:00:00 nginx: worker process

杀掉nginx

pkill nginx

nginx -s stop

nginx访问

在浏览器中输入nginx运行服务器的IP,即可访问,比如192.168.1.100,会出现以下内容

Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

[root@phoenix nginx-1.13.7]# curl -I 192.168.1.100
HTTP/1.1 200 OK
Server: WS
Date: Sun, 05 Jan 2020 11:51:05 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sun, 05 Jan 2020 11:19:46 GMT
Connection: keep-alive
ETag: "5e11c652-264"
Accept-Ranges: bytes

docker中安装nginx简记

下面是在docker中创建centos7并安装nginx的简记

docker run -itd --name ngx  -h ngx --net=host -v /disk/:/disk -v /opt:/opt -v /tmp:/tmp  cent7 bash
docker start ngx
docker exec -it ngx bash
yum install -y net-tools
yum install -y libaio numactl
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

wget http://nginx.org/download/nginx-1.13.7.tar.gz

tar -xvf nginx-1.13.7.tar.gz

cd nginx-1.13.7

sed -i -e 's/1.13.7//g' -e 's/nginx//WS/g' -e 's/"NGINX"/"WS"/g' src/core/nginx.h

useradd black

./configure --prefix=/usr/local/nginx --user=black --group=black --with-http_stub_status_module --with-http_ssl_module

make
make install

export PATH=/usr/local/nginx/sbin:$PATH

nginx目录

nginx默认发布目录为html目录

[root@ngx nginx]# pwd
/usr/local/nginx
[root@ngx nginx]# ll
total 36
drwx------ 2 black root 4096 Jan  5 07:55 client_body_temp
drwxr-xr-x 2 root  root 4096 Jan  5 07:54 conf
drwx------ 2 black root 4096 Jan  5 07:55 fastcgi_temp
drwxr-xr-x 2 root  root 4096 Jan  5 07:54 html
drwxr-xr-x 2 root  root 4096 Jan  5 07:55 logs
drwx------ 2 black root 4096 Jan  5 07:55 proxy_temp
drwxr-xr-x 2 root  root 4096 Jan  5 07:54 sbin
drwx------ 2 black root 4096 Jan  5 07:55 scgi_temp
drwx------ 2 black root 4096 Jan  5 07:55 uwsgi_temp

默认访问主页

[root@ngx nginx]# ll html/index.html 
-rw-r--r-- 1 root root 612 Jan  5 07:54 html/index.html

 这里目录放的是静态文件,现在流行的vue-cli前端打包的静态文件就可以直接简单地放在这里

下载一个vue模板简单修改一下,然后编译打包生成静态文件

npm run build

cp -r /opt/code/dist/* ./html/

不需要重启nginx,再次访问127.0.0.1,就可以看到页面内容已经变化

 nginx配置

nginx默认配置文件

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

[root@ngx nginx]# ll conf/nginx.conf
-rw-r--r-- 1 root root 2656 Jan  5 07:54 conf/nginx.conf

// 全局区

//启动的用户与组

user  black black;


// 开启1个子进程不超过 CPU*核数,即逻辑CPU个数,前提是该服务器只用于nginx
worker_processes 1;

 

worker_cpu_affinity参数

2核cpu,开启2个进程

worker_processes     2;
worker_cpu_affinity 01 10;
01表示启用第一个CPU内核,10表示启用第二个CPU内核 
worker_cpu_affinity 01 10;表示开启两个进程,第一个进程对应着第一个CPU内核,第二个进程对应着第二个CPU内核。

2核cpu,开启4个进程

worker_processes     4;
worker_cpu_affinity 01 10 01 10;
4个cpu,开启4个进程

worker_processes     4;
worker_cpu_affinity 0001 0010 0100 1000;

0001表示启用第一个CPU内核,0010表示启用第二个CPU内核,依此类推
4核cpu,开启2个进程

worker_processes     2;
worker_cpu_affinity 0101 1010;

0101表示开启第一个和第三个内核,1010表示开启第二个和第四个内核;2个进程对应着四个内核;
worker_cpu_affinity配置是写在/etc/nginx/nginx.conf里面的;2核是 01,四核是0001,
8核是00000001,有多少个核,就有几位数,1表示该内核开启,0表示该内核关闭。
8核cpu,开启8个进程

worker_processes 8;

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

worker_processes最多开启8个,8个以上性能提升不会再提升了,而且稳定性变得更低,所以8个进程够用了

性能测试,在服务器上执行top,然后按1,就可以看到cpu工作情况,如果多个cpu内核的利用率差不多,就证明nginx已经成功利用了多核cpu,测试结束后,cpu内核的负载都同时降低

worker_rlimit_nofile 102400;

一个nginx进程最多打开的文件数,最好与 ulimit -n 一致

 

全局错误日志及PID文件,日志等级{debug | info | notice | warn | error }

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
logs是指nginx安装目录下的logs目录,这里可以使用全路径,比如

pid     /usr/local/nginx/nginx.pid

 

 

Events {

 use epoll;      //多路复用IO,要求linux2.6以上内核,可提高nginx性能,是大大提高

 worker_connections  1024; // 一个子进程最大允许连1024个连接

 multi_accept on;         //尽可能多地接受请求

}

 

//http是nginx的一个模块,是一个应用段

http {  //配置http服务器,利用其反向代理功能提供负载均衡支持

 

    //一个页面可能会包括图片、文字、视频等,该行将不同格式的内容转换为其对应的数据格式,比如title.ico转化为title/ico,文字转化为text/html

    include       mime.types; 

    //什么是mime可参考 https://blog.csdn.net/Vito_Jianxue/article/details/81328304

    //mime.types 常见类型可参考 https://www.cnblogs.com/wangzaiplus/p/10815430.html

    //比如,发送邮件,让邮件的内容显示为html时,需要指定content-type为text/html
    default_type  application/octet-stream;  //指 bin exe dll,就是二进制流,通常用于下载、传输文件

    //实际上,该类型同样支持一个普通网站的请求与响应,但配置为该类型后,该网站还可以提供下载功能

 

    //指定日志格式

    log_format main '$remote_addr - $remote_user [$time_local] '
                               '"$request" $status $bytes_sent '
                               '"$http_referer" "$http_user_agent" '
                               '"$request_time $pipe" '
                               '"$http_routerule" '
                               '"$gzip_ratio"';

 

 

    access_log /usr/local/nginx/logs/nginx/access.log;  //指定访问的日志位置

 

    // 使用 zero copy 方式传送文件,普通网站必开,只提供下载功能时可关闭

    sendfile        on; 

    //什么是零copy,可参考 https://baijiahao.baidu.com/s?id=1648595456047501430&wfr=spider&for=pc

 

    keepalive_timeout 60; //超时时间60秒;保持一个客户端与服务器端的连接有效时间为60秒

    //tcp通信需要三次握手建立一个安全连接,打开一页面,看了30秒后点击一个按钮向服务器发送一个信息,

    //此时,由于在60秒内,不会重新握手建立新的连接,而是使用同一个连接进行交互;

    //如果超过60秒,点击页面上的按钮向服务器发送信息,那么就会重新进行三次握手建立新的连接

 

    //nginx 代理后端(java/go/php等)程序的超时时间

    proxy_connect_timeout 90;  //连接超时

    proxy_send_timeout 90;     //nginx发送数据到后端的超时时间,nginx发,后端接收

    proxy_read_timeout 90;      //nginx接收后端数据的超时时间,nginx收,后端发送

   

     //主配置文件默认为nginx.conf,但有时配置内容太多,把一些配置写到一个单独的文件中,通过这种方式再引入进来

     include vhosts.conf;

 

     Server1 { // 这是虚拟主机段,一个server通常对应一个网站应用平台

        listen       80;
        server_name  localhost;    //域名,一个指向本机的域名

         access_log             /tmp/logs/access.log main;

 

        //nginx由内核和模板组成,内核匹配请求,此处会匹配根目录,是URL请求的根目录,即访问IP:端口转向的目录
        location / {
            root   html;  //root模块定义应用发布目录·根目录,nginx安装目录下的html目录
            index  index.html index.htm;  //index定义主页面,访问项目就转到此处定义的页面
        }

 

        //如果网站出现500、502、503、504等错误,就将请求重置到"/50x.html"
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;    //50x.html文件位于html目录下
        }

     }

 

     Server2 {  //一个nginx中可以配置多个应用,每个应用都有自己的端口

     }

}

 

 静态页面访问及文件下载

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

下面描述具体的配置方式,以VUE为例,实际上就是以静态文件为例

安装一个VUE手脚架(略)

vue init webpack vue-demo

cd vue-demo

yarn install/npm install/cnpm install 三者用其一

npm run build

cp -r dist/ /opt/code/vue_demo

root@db:~# ls /opt/code/vue_demo/
index.html  static

 一个静态页面以及一个静态目录,页面的内容有图片、文字、链接,即常见网站首页面的风格

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
        <meta name=viewport content="width=device-width,initial-scale=1">
        <title>mango-ui</title>
        <link href=/static/css/app.30790115300ab27614ce176899523b62.css rel=stylesheet>
    </head>
    <body>
        <div id=app></div>
        <script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script>
        <script type=text/javascript src=/static/js/vendor.43deb552719d04ea7ed2.js></script>
        <script type=text/javascript src=/static/js/app.b22ce679862c47a75225.js></script>
    </body>
</html>

 cp /usr/local/nginx/html/50x.html /opt/code/vue_demo/

修改nginx配置

worker_processes  1;

error_log  logs/error.log  info;
pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;


        location / {
            root   /opt/code/vue_demo/;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /opt/code/vue_demo/;
        }
    }

}

  

 重启nginx

nginx -s reload

 

页面访问

http://127.0.0.1/

 

文件下载上面的配置就可以提供局域网内文件下载功能,将常用的软件放于指定的位置,

不需要重启nginx,放完就可以使用,因为nginx是epoll事件响应模式,用时才触发一个事件,不是把所有东西都放到内存

mkdir /opt/code/vue_demo/static/download

cp nginx-1.13.7.tar.gz /opt/code/vue_demo/static/download/

tan@db:/tmp$ mkdir /tmp/test
tan@db:/tmp$ cd /tmp/test
tan@db:/tmp/test$ wget http://127.0.0.1/static/download/nginx-1.13.7.tar.gz
--2020-01-06 00:06:47--  http://127.0.0.1/static/download/nginx-1.13.7.tar.gz
Connecting to 127.0.0.1:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 990836 (968K) [application/octet-stream]
Saving to: ‘nginx-1.13.7.tar.gz’

nginx-1.13.7.tar.gz                                100%[===============================================================================================================>] 967.61K  --.-KB/s    in 0.001s  

2020-01-06 00:06:47 (631 MB/s) - ‘nginx-1.13.7.tar.gz’ saved [990836/990836]

 nginx反向代理示例-动态代理

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

 描述

nginx端口9000,网站端口9003,通过nginx9000端口再转向9003

nginx配置

worker_processes  1;

error_log  logs/error.log  info;
pid        logs/nginx.pid;


events {
    worker_connections  1024;
}



http{
    include                         mime.types;
    default_type                    application/octet-stream;
    keepalive_timeout               65;
    proxy_connect_timeout           90; 
    proxy_read_timeout              600; 
    proxy_send_timeout              180; 

    upstream gin_login {
        server 127.0.0.1:9003;
    }

    server {
        listen      9000;
        server_name localhost;
        charset     utf-8;
        access_log  /var/log/ngix_access.log;
        error_log   /var/log/ngix_error.log;
        

        location / {
            root   /opt/code/vue_demo/;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /opt/code/vue_demo/;
        }
        location /static {
            alias /opt/code/vue_demo/static/;
        }

        location /loginJson {
            proxy_pass http://gin_login;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

 访问,可以通过nginx的9000端口访问9003端口网站提供的服务,9003可以是 java/go/php/python 等后端服务,这就是“反向代理”

[root@ngx conf]# curl http://127.0.0.1:9003/loginJson -H 'content-type: application/json' -d '{ "user": "root","password": "rootroot" }'
{"token":"root_201344486"}
[root@ngx conf]# 
[root@ngx conf]# 
[root@ngx conf]# curl http://127.0.0.1:9000/loginJson -H 'content-type: application/json' -d '{ "user": "root","password": "rootroot" }'
{"token":"root_201344486"}

另外,9000端口指向的VUE静态网站依然是可以访问的

http://127.0.0.1:9000/#/

同时,之前的下载功能一样可以使用

wget http://127.0.0.1:9000/static/download/nginx-1.13.7.tar.gz

nginx通过内核匹配请求路径,代理了多个服务

  nginx反向代理示例-负载均衡

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

 配置,把上面示例的upstream 部分替换为以下部分

upstream gin_login {
        server 127.0.0.1:9003 weight=1 max_fails=2 fail_timeout=30s;
        server 127.0.0.1:9004 weight=1 max_fails=2 fail_timeout=30s;
    }

nginx 9000端口代理 9003,9004两个服务,权重为1:1,轮询模式;一个请求代理到9003,那么下一个请求必将代理9004;

如果9003挂了,那么所有的请求代理到9004,不会出现9003无法访问的情况。

上面的配置表示30秒内检测服务不可用的次数,如果失败超过2次,则不再尝试该端口服务,即剔除负载均衡。

这就是nginx轮询模式的负载均衡。

原文地址:https://www.cnblogs.com/perfei/p/12153019.html