nginx

作者: Liang_JC | 来源:发表于2020-05-13 23:00 被阅读0次

    IO模型

    • 阻塞IO模型

      应用程序接收到用户一个请求,应用程序发起系统调用内核完成工作,内核从网络或者硬盘上得到数据,发往应用程序的用户空间中,此时应用程序一直处于等待状态,不能做任何事

    • 同步非阻塞IO模型

      应用程序接收到用户一个请求,应用程序发起系统调用内核完成工作,应用程序发起调用后处于空闲状态,不用等待系统回应,所以应用程序会不断询问系统处理结果。当系统处理完毕后就会回应并发往应用程序的用户空间

    • I/O多路复用模型

      多个app发起请求,select进程接受请求,select进程发往内核处理,如果内核已把数据准备好了,发信息给app(在此之前app处于阻塞状态),此时app参与了复制过程,内核把数据复制到用户空间并返回了成功结果,app就可以进行通讯了

    • 信号驱动IO模型

      app进程发起系统调用后,有异步行为,内核准备数据发到内核发送数据到用户空间期间不阻塞(app可以做其他事)

      优点:线程并没有在等待数据时被阻塞,可以提高资源的利用率

      缺点:信号 I/O 在大量 IO 操作时可能会因为信号队列溢出导致没法通知

    • 异步IO模型

      app进程发起系统调用后,由内核完成,内核在处理过程中app全都不阻塞

      优点:异步 I/O 能够充分利用 DMA 特性,让 I/O 操作与计算重叠

      缺点:要实现真正的异步 I/O,操作系统需要做大量的工作。目前 Windows 下通过 IOCP 实现了真正的异步 I/O,在 Linux 系统下,Linux 2.6才引入,目前AIO 并不完善,因此在 Linux 下实现高并发网络编程时以 IO 复用模型模式+多线程任务的架构基本可以满足需求

    这五种 I/O 模型中,越往后,阻塞越少,理论上效率也是最优前四种属于同步I/O,因为其中真正的 I/O 操作(recvfrom)将阻塞进程/线程,只有异步 I/O 模型才与 POSIX 定义的异步 I/O 相匹配

    主要实现方式有以下几种:
    Select:Linux实现对应,I/O复用模型,BSD4.2最早实现,POSIX标准,一般操作系统均有实现,apache工作机制

    Select:POSIX所规定,目前几乎在所有的平台上支持,其良好跨平台支持也是它的一个优点,本质上是通过设置或者检查存放fd标志位的数据结构来进行下一步处理

    缺点
    ● 单个进程能够监视的文件描述符的数量存在最大限制,在Linux上一般为1024,可以通过修改宏定义FD_SETSIZE,再重新编译内核实现,但是这样也会造成效率的降低
    ● 单个进程可监视的fd数量被限制,默认是1024,修改此值需要重新编译内核
    ● 对socket是线性扫描,即采用轮询的方法,效率较低
    ● select 采取了内存拷贝方法来实现内核将 FD 消息通知给用户空间,这样一个用来存放大量fd的数据结构,这样会使得用户空间和内核空间在传递该结构时复制开销大Poll:Linux实现,对应I/O复用模型,System V unix最早实现

    Poll:Linux实现,对应I/O复用模型,System V unix最早实现

    ● 本质上和select没有区别,它将用户传入的数组拷贝到内核空间,然后查询每个fd对应的设备状态
    ● 其没有最大连接数的限制,原因是它是基于链表来存储的
    ● 大量的fd的数组被整体复制于用户态和内核地址空间之间,而不管这样的复制是不是有意义
    ● poll特点是“水平触发”,如果报告了fd后,没有被处理,那么下次poll时会再次报告该fd
    ● 边缘触发:只通知一次

    Epoll:Linux特有,对应I/O复用模型,具有信号驱动I/O模型的某些特性,nginx工作机制

    ● 支持水平触发LT和边缘触发ET,最大的特点在于边缘触发,它只告诉进程哪些fd刚刚变为就需态,并且只会通知一次
    ● 使用“事件”的就绪通知方式,通过epoll_ctl注册fd,一旦该fd就绪,内核就会采用类似callback的回调机制来激活该fd,epoll_wait便可以收到通知

    优点:
    ● 没有最大并发连接的限制:能打开的FD的上限远大于1024(1G的内存能监听约10万个端口),具体查看/proc/sys/fs/file-max,此值和系统内存大小相关
    ● 效率提升:非轮询的方式,不会随着FD数目的增加而效率下降;只有活跃可用的FD才会调用callback函数,即epoll最大的优点就在于它只管理“活跃”的连接,而跟连接总数无关
    ● 内存拷贝,利用mmap(Memory Mapping)加速与内核空间的消息传递;即epoll使用mmap减少复制开销

    Kqueue:FreeBSD实现,对应I/O复用模型,具有信号驱动I/O模型某些特性,linux不支持

    /dev/poll:SUN的Solaris实现,对应I/O复用模型,具有信号驱动I/O模型的某些特性Iocp Windows实现,对应第5种(异步I/O)模型 ,linux不支持

    nginx源码编译安装

    cd /usr/local/src
    yum install git  gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed -y
    tar xf nginx-1.16.1.tar.gz 
    git clone https://github.com/openresty/echo-nginx-module.git
    cd nginx-1.16.1/
    groupadd -g 981 nginx
    useradd -r -g 981 -u 987 -s /sbin/nologin nginx
    ./configure \
    --prefix=/apps/nginx \
    --user=nginx --group=nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-http_perl_module \
    --with-pcre \
    --with-stream \
    --with-stream_ssl_module \
    --with-stream_realip_module \
    --add-module=/usr/local/src/echo-nginx-module
    make && make install
    

    nginx虚拟主机

    cd /apps/nginx/
    cp -a conf/nginx.conf conf/nginx.conf.bak
    vim conf/nginx.conf
    http {
        ...
        sendfile        on; #开启后nopush才有效
        tcp_nopush      on; #性能优化
        tcp_nodelay     on; #性能优化
        keepalive_timeout  65; #保持连接超时时长
        include "/apps/nginx/conf.d/*.conf";
        ...
    }
    mkdir conf.d
    vim conf.d/test.conf
    server_tokens off;
    server {
        server_name www.magedu.net;
        root /data/site1/;
    }
    server {
        server_name www.magedu.org;
        root /data/site2/;
    }
    mkdir /data/site{1,2}
    echo site1 > /data/site1/index.html
    echo site2 > /data/site2/index.html
    
    ln -s /apps/nginx/sbin/nginx /sbin/
    nginx -t        #检查配置文件
    nginx           #启动nginx
    
    #client
    http://www.magedu.net
    http://www.magedu.org
    

    nginx:location

    vim conf.d/test.conf
    server_tokens off;
    server {
        server_name www.magedu.net;
        root /data/site1/;
        location /echo {
            default_type text/html;
            echo hello_world;
        }
        location /about {
            alias /apps/nginx/html;  #别名
            index index.html;
        }
        location /images {
            alias /data/images;
            try_files $uri $uri.jpg =404;   #先找uri(uri=/images/{这个值}),再找$uri/defalut.jpg,都找不到就404
        }
        error_page 404 /40x.html;     #错误重定向
        location = /40x.html {}
    }
    server {
        server_name www.magedu.org;
        root /data/site2/;
    }
    echo 404-error > /data/site1/40x.html
    cp /usr/share/backgrounds/day.jpg /data/images/
    nginx -s reload     #重新加载配置文件
    
    #client
    http://www.magedu.net/echo
    http://www.magedu.net/about
    http://www.magedu.net/111111.html
    http://www.magedu.net/images/day.jpg
    

    访问控制

    yum install httpd-tools
    htpasswd -b -c conf.d/.nginx_passwd alice centos
    htpasswd -b conf.d/.nginx_passwd bob centos
    vim conf.d/test.conf 
    server_tokens off;
    server {
        server_name www.magedu.net;
        root /data/site1/;
        location /admin {
            root /data;
            allow 192.168.37.0/24;
            deny all;
            auth_basic "admin area";
            auth_basic_user_file /apps/nginx/conf.d/.nginx_passwd;
        }
    }
    mkdir /data/admin
    echo admin > /data/admin/index.html
    
    #client
    http://www.magedu.net/admin
    

    status页面

    vim conf.d/test.conf 
    server_tokens off;
    server {
        server_name www.magedu.net;
        root /data/site1/;
        location /status {
            stub_status;
            allow 127.0.0.1;
            allow 192.168.37.0/24;
            deny all;
        }
    }
    
    #client
    http://www.magedu.net/status
    

    log 格式 json

    vim conf/nginx.conf
    http {
        log_format access_json '{"@timestamp":"$time_iso8601",'
            '"host":"$server_addr",'
            '"clientip":"$remote_addr",'
            '"size":$body_bytes_sent,'
            '"responsetime":$request_time,'
            '"upstreamtime":"$upstream_response_time",'
            '"upstreamhost":"$upstream_addr",'
            '"http_host":"$host",'
            '"uri":"$uri",'
            '"domain":"$host",'
            '"xff":"$http_x_forwarded_for",'
            '"referer":"$http_referer",'
            '"tcp_xff":"$proxy_protocol_addr",'
            '"http_user_agent":"$http_user_agent",'
            '"status":"$status"}';
        access_log logs/access_json.log access_json;
    }
    vim conf.d/test.conf 
    server_tokens off;
    server {
        server_name www.magedu.net;
        root /data/site1/;
        location /echo {
            default_type text/html;
            echo hello_world;
        }
        error_page 404 /40x.html;
        location = /40x.html {}
    
        location /admin {
            root /data;
            allow 192.168.37.0/24;
            deny all;
            auth_basic "admin area";
            auth_basic_user_file /apps/nginx/conf.d/.nginx_passwd;
        }
        location /status {
            stub_status;
            allow 127.0.0.1;
            allow 192.168.37.0/24;
            deny all;
        }
        access_log logs/magedu_net.access.log access_json;
    }
    

    启用压缩

    vim conf.d/test.conf 
    server {
        server_name www.magedu.net;
        root /data/site1/;
        access_log logs/magedu_net.access.log access_json;
        gzip on;                #启用压缩
        gzip_comp_level 6;      #压缩等级
        gzip_min_length 64;     #响应报文阈值
        gzip_vary on;           #响应报文首部插入“Vary: Accept-Encoding”  
        gzip_types text/xml text/css application/javascript;    #压缩类型
        location /download {
            autoindex on;                   #自动文件索引功能,默为off
            autoindex_exact_size off;       #计算文件确切大小(单位bytes),off 显示大概大小(单位K、 M),默认on
            autoindex_localtime on;         #显示本机时间而非GMT(格林威治)时间,默认off
            #autoindex_format json;         #显示索引的页面文件风格,默认html,格式:html|xml|json|jsonp
            #limit_rate 100k;               #限速
            index index.html;
        }
    }
    mkdir /data/site1/download
    mount /dev/sr0 /data/site1/download
    nginx -s reload
    umount /dev/sr0
    cp -a /var/log/messages /data/site1/download/m.html
    
    #client
    http://www.magedu.net/download
    curl -I http://www.magedu.net/download/m.html
    

    ssl

    #生成CA证书
    cd /etc/pki/tls/certs/
    vim Makefile
        #/usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@
        /usr/bin/openssl genrsa $(KEYLEN) > $@
    make magedu.net.crt
    CN
    beijing
    beijing
    magedu.net
    opt
    www.magedu.net
    
    mkdir /apps/nginx/ssl
    mv magedu.net.* /apps/nginx/ssl
    
    #配置支持https
    cd /apps/nginx
    vim conf.d/test.conf 
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.net;
        root /data/site1/;
        ssl_certificate /apps/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        gzip on;                        #启用压缩
        gzip_comp_level 6;              #压缩等级
        gzip_min_length 64;             #响应报文阈值
        gzip_vary on;                   #响应报文首部插入“Vary: Accept-Encoding”  
        gzip_types text/xml text/css application/javascript;    #压缩类型
        access_log logs/magedu_net.access.log access_json;    
        location / {
            if ( $scheme = http ) {
                return 301 https://www.magedu.net;      #重定向到https
            }
        }
    } 
    nginx -s reload
    
    #client
    http://www.magedu.net
    curl -kL http://www.magedu.net
    

    rewrite模块

    vim conf.d/test.conf 
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.net;
        root /data/site1/;
        ssl_certificate /apps/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        gzip on;                        #启用压缩
        gzip_comp_level 6;              #压缩等级
        gzip_min_length 64;             #响应报文阈值
        gzip_vary on;                   #响应报文首部插入“Vary: Accept-Encoding”  
        gzip_types text/xml text/css application/javascript;    #压缩类型
        access_log logs/magedu_net.access.log access_json;    
        location / {
            if ( $scheme = http ) {
                rewrite ^/(.*)$ https://www.magedu.net/$1 permanent;        #重定向到https
            }
            if ( $http_user_agent ~* curl ){                #curl浏览器禁止访问
                return 403;
            }
            if ( !-f $request_filename ) {                  #错误页面重定向到主页
                rewrite ^/(.*)$ http://www.magedu.net/index.html;
            }
        }
    } 
    
    #client
    http://www.magedu.net
    curl -kL http://www.magedu.net
    curl -kL -A IE http://www.magedu.net
    http://www.magedu.net/223123.html
    
    #多个https(apache不支持多个https)
    cd /etc/pki/tls/certs/
    make magedu.org.crt
    CN
    beijing
    beijing
    magedu.org
    opt
    www.magedu.org
    
    mv magedu.org.* /apps/nginx/ssl/
    cd /apps/nginx
    vim conf.d/test.conf
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.net;
        root /data/site1/;
        ssl_certificate /apps/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        gzip on;                        #启用压缩
        gzip_comp_level 6;              #压缩等级
        gzip_min_length 64;             #响应报文阈值
        gzip_vary on;                   #响应报文首部插入“Vary: Accept-Encoding”  
        gzip_types text/xml text/css application/javascript;    #压缩类型
        access_log logs/magedu_net.access.log access_json;    
        location / {
            if ( $scheme = http ) {
                rewrite ^/(.*)$ https://www.magedu.net/$1 permanent;        #重定向到https
            }
            if ( $http_user_agent ~* curl ){                #curl浏览器禁止访问
                return 403;
            }
            if ( !-f $request_filename ) {                  #错误页面重定向到主页
                rewrite ^/(.*)$ http://www.magedu.net/index.html;
            }
        }
    } 
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.org;
        root /data/site2/;
        ssl_certificate /apps/nginx/ssl/magedu.org.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.org.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        access_log logs/magedu_org.access.log access_json;
        location / {
            if ( $scheme = http ) {
                rewrite ^/(.*)$ https://www.magedu.org/$1 redirect;
            }
            if ( !-f $request_filename ) {
                rewrite ^/(.*)$ http://www.magedu.org/index.html;
            }
        }
    }
    nginx -s reload
    
    #client
    http://www.magedu.net
    http://www.magedu.org
    

    referer 防盗链

    cp /var/www/html/wordpress/wp-content/themes/twentyseventeen/assets/images/coffee.jpg /data/site2/
    vim /data/site1/daolian.html
    <img src=http://www.magedu.org/coffee.jpg>
    
    vim conf.d/test.conf
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.net;
        root /data/site1/;
        ssl_certificate /apps/nginx/ssl/magedu.net.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.net.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        gzip on;                        #启用压缩
        gzip_comp_level 6;              #压缩等级
        gzip_min_length 64;             #响应报文阈值
        gzip_vary on;                   #响应报文首部插入“Vary: Accept-Encoding”  
        gzip_types text/xml text/css application/javascript;    #压缩类型
        access_log logs/magedu_net.access.log access_json;    
        location / {
            if ( !-f $request_filename ) {                  #错误页面重定向到主页
                rewrite ^/(.*)$ http://www.magedu.net/index.html;
            }
        }
    } 
    server {
        listen 80;
        listen 443 ssl;
        server_name www.magedu.org;
        root /data/site2/;
        ssl_certificate /apps/nginx/ssl/magedu.org.crt;
        ssl_certificate_key /apps/nginx/ssl/magedu.org.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        access_log logs/magedu_org.access.log access_json;
        location / {
            if ( $scheme = http ) {
                rewrite ^/(.*)$ https://www.magedu.org/$1 redirect;
            }
            if ( !-f $request_filename ) {
                rewrite ^/(.*)$ http://www.magedu.org/index.html;
            }
        }
        valid_referers none block server_names *.magedu.org  ~\.google\. ~\.baidu\.;    #除了定义的域名,其他不允许链接,防盗链
        if ($invalid_referer) {
            return 403 "Forbidden Access";
        }
    }
    
    #client
    http://www.magedu.net/daolian.html
    

    实现fastcgi

    #server
    1、安装新版php-fpm
    yum install -y http://mirrors.ustc.edu.cn/remi/enterprise/remi-release-7.rpm
    yum install -y php73-php-fpm php73-php-mysql mariadb
    vim /etc/opt/remi/php73/php-fpm.d/www.conf
        user = nginx
        group = nginx
        listen = 9000
        ;listen.allowed_clients = 127.0.0.1     #注释掉
        pm.status_path = /fpm_status
        ping.path = /ping
    
    2、配置nginx支持fastcgi
    vim conf.d/test.conf
    server_tokens off;
    server {
        listen 80;
        server_name www.magedu.net;
        root /data/php;
        index index.php indexl.html;
        access_log logs/magedu_net.access.log access_json;
    
        location ~* \.php$ {
            root /data/php;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
        location ~* ^/(fpm_status|ping)$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
            include fastcgi_params;
        }
    }
    
    3、创建mysql用户
    systemctl start mariadb
    mysql -e 'create database wordpress;grant all on wordpress.* to wpuser@"localhost" identified by "centos";flush privileges;'
    
    4、开启php-fpm缓存
    vim conf/nginx.conf
    http {
        fastcgi_cache_path /var/cache/nginx/fcgi_cache levels=1:2:1 keys_zone=fcgicache:20m inactive=120s;
        ...
    }
    vim conf.d/test.conf
    server {
        ...
        #开启fastcgi缓存
        fastcgi_cache fcgicache;
        fastcgi_cache_key $request_uri;
        fastcgi_cache_valid 200 302 10m;
        fastcgi_cache_valid 301 1h;
        fastcgi_cache_valid any 1m;
    }
    
    5、安装php网站
    wget https://cn.wordpress.org/wordpress-5.4.1-zh_CN.tar.gz
    mkdir /data/php
    tar xf wordpress-5.4.1-zh_CN.tar.gz
    cp -r "wordpress/*" /data/php/
    cp /data/php/wp-config-sample.php /data/php/wp-config.php
    vim /data/php/wp-config.php
    define( 'DB_NAME', 'wordpress' );
    define( 'DB_USER', 'wpuser' );
    define( 'DB_PASSWORD', 'centos' );
    define( 'DB_HOST', 'localhost' );
    mkdir /data/php/wp-content/uploads
    setfacl -R -m u:nginx:rwx /data/php/
    systemctl start mariadb
    
    6、启动服务
    systemctl start php-fpm
    nginx -s reload
    
    #client
    http://www.magedu.net/index.php
    http://www.magedu.net/fpm_status
    http://www.magedu.net/fpm_status?full
    http://www.magedu.net/fpm_status?xml
    http://www.magedu.net/fpm_status?json
    

    反向代理(调度)

    #环境:3台机器    A:nginx B:rs1  C:rs2
    
    #nginx-server
    vim conf/nginx.conf
    http {
        proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;  
        ...
    }
    vim conf.d/test.conf 
    server_tokens off;
    server {
        listen 80;
        server_name www.magedu.net ;
        root /data/site1/;
        access_log logs/magedu_net.access.log access_json;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 1h;
        proxy_cache_valid any 1m;
        proxy_hide_header Etag;                 #隐藏ETAG
        #proxy_pass_header Server;              #后端软件版本号替换为前端版本号
        location ~* ^.*\.(jpg|gif|bmp|jpeg)$ {      
            proxy_pass http://192.168.37.37;
        }
        location /api {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    #真实的访问IP地址
            proxy_pass http://192.168.37.47;        #结果是:http://192.168.37.47/api
            #proxy_pass http://192.168.37.47/;      #最后加"/"就等于跳转到47的根下
        }
    }
    mkdir /var/cache/nginx/
    
    #rs1
    yum install httpd -y
    echo 37 > /var/www/html/index.html
    cp /usr/share/pixmaps/faces/legacy/sky.jpg /var/www/html/
    vim /etc/httpd/conf/httpd.conf
    <IfModule log_config_module>
        LogFormat "\"%{X-Forwarded-For}i\" %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
        ....
    </IfModule>
    systemctl start httpd
    
    #rs2
    yum install httpd -y
    mkdir /var/www/html/api
    echo 47 > /var/www/html/index.html
    echo api > /var/www/html/api/index.html
    vim /etc/httpd/conf/httpd.conf
    <IfModule log_config_module>
        LogFormat "\"%{X-Forwarded-For}i\" %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
        ....
    </IfModule>
    systemctl start httpd
    
    #client
    http://www.magedu.net/sky.jpg
    http://www.magedu.net/api
    

    实现均衡高可用反向代理

    #环境:3台机器    A:nginx B:rs1  C:rs2
    
    vim conf/nginx.conf
    http {
        upstream web {      
            server 192.168.37.37:80;
            server 192.168.37.47:80 weight=2;
            #server 192.168.37.47:80 down;
            server 127.0.0.1:80 backup;         #down机后sorry-server
            #hash $cookie_sessionid;            #调度算法,默认:wrr
        }
    }
    vim conf.d/test.conf
    server_tokens off;
    server {
        listen 80;
        server_name www.magedu.net;
        root /data/site1/;
        access_log logs/magedu_net.access.log access_json;
    
        location / {
            proxy_pass http://web;                  
        }  
        location /echo {
            echo cookie;
            echo $cookie_sessioned;
        }
    }
    server {
        listen 8080;
        root /data/site3;
        index index.html;
        access_log logs/magedu_net.sorry.access.log access_json;
    }
    mkdir /data/site3
    echo sorry > /data/site3/index.html
    systemctl restart php73-php-fpm mariadb.service
    nginx -s reload
    
    #client
    while true;do curl www.magedu.net;sleep 0.5;done
    
    #测试rs1、rs2分别停用httpd服务
    

    四层代理

    #环境:3台机器    A:nginx B:rs1  C:rs2
    
    #rs1
    yum install -y mariadb-server
    systemctl start mariadb
    mysql -e "create database db37;grant all on *.* to test@'192.168.37.%' identified by 'centos';flush privileges"
    
    #rs2
    yum install -y mariadb-server
    systemctl start mariadb
    mysql -e "create database db47;grant all on *.* to test@'192.168.37.%' identified by 'centos';flush privileges"
    
    #nginx-server
    vim conf/nginx.conf
    #独立体,不在http{}里面
    stream {
            upstream mysql {
                    server 192.168.37.37:3306;
                    server 192.168.37.47:3306;
                    least_conn;
            }
            server {
                    listen 192.168.37.27:3306;
                    proxy_pass mysql;
            }
    }
    nginx -s reload
    
    #client
    mysql -utest -pcentos -h192.168.37.27 -e "show databases"
    

    tengine编译安装

    #准备工作
    yum install gcc pcre-devel openssl-devel zlib-devel
    cd /usr/local/src/
    wget http://tengine.taobao.org/download/tengine-2.1.2.tar.gz        #此版本不支持传输层反向代理
    tar xf tengine-2.1.2.tar.gz 
    cd tengine-2.1.2/
    useradd -r -s /sbin/nologin nginx
    
    #编译安装
    ./configure --prefix=/apps/tengine \
    --user=nginx \
    --group=nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-pcre \
    --with-http_concat_module       #tengine特有模块
    make && make install
    
    #使用
    cd /apps/tengine
    vim conf/nginx.conf
    server {
        location / {
                root   html;
                index  index.html index.htm;
                concat on;
        }
    }
    sbin/nginx -t
    sbin/nginx
    

    实现keepalived高可用反向代理

    #环境:4台机器    A:ka1  B:ka2  C:rs1  D:rs2
    
    #ka1
    #配置邮件
    vim ~/.mailrc   #或 /etc/mail.rc
    set from=184116857@qq.com
    set smtp=smtp.qq.com
    set smtp-auth-user=184116857@qq.com
    set smtp-auth-password=lzhdjmtznbftbiai
    set smtp-auth=login
    set ssl-verify=ignore
    
    #配置keepalived
    yum install keepalived -y
    vim /etc/keepalived/keepalived.conf
    global_defs {
       notification_email {
         admin@magedu.net       #发给本机root邮件
       }
       notification_email_from ka1@magedu.net
       smtp_server 127.0.0.1    #发邮件的地址
       smtp_connect_timeout 30
       router_id ka1        #主机名    
       vrrp_mcast_group4 224.0.0.100    #D类地址,多播
    }
    vrrp_script chk_down {      #自定义脚本
        script "/etc/keepalived/chk_down.sh"
        interval 1
        weight -30
    }
    vrrp_script chk_nginx {
        script "/etc/keepalived/chk_nginx.sh"
        interval 1
        weight -30
    }
    vrrp_instance VI_1 {    #虚拟路由器
        state MASTER        #在另一个结点上为BACKUP
        interface eth0      #网卡接口
        virtual_router_id 10    #多个节点必须相同
        priority 100        #优先级,在另一个结点上要小于这个值
        advert_int 1        #通告间隔1s
        authentication {
            auth_type PASS  #预共享密钥认证
            auth_pass 123456    #密码
        }
        virtual_ipaddress {
            192.168.37.100/24 dev eth0 label eth0:1
        }
        track_script {      #引用脚本
            chk_down
            chk_nginx
        }
        notify_master "/etc/keepalived/notify.sh master"
        notify_backup "/etc/keepalived/notify.sh backup"
        notify_fault "/etc/keepalived/notify.sh fault"
    }
    
    vim /etc/keepalived/notify.sh
    #!/bin/bash
    contact='root@localhost'
    notify() {
        mailsubject="$(hostname) to be $1, vip floating"
        mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
        echo "$mailbody" | mail -s "$mailsubject" $contact
    }
    case $1 in
    master)
        notify master
        ;;
    backup)
        notify backup
        /usr/sbin/nginx
        ;;
    fault)
        notify fault
        ;;
    *)
        echo "Usage: $(basename $0) {master|backup|fault}"
        exit 1
        ;;
    esac
    echo '[ -f /etc/keepalived/down ] && exit 1 || exit 0' > /etc/keepalived/chk_down.sh
    echo 'killall -0 nginx &> /dev/null && exit 0 || exit 1' > /etc/keepalived/chk_nginx.sh
    sed -i '1i\#!/bin/bash' /etc/keepalived/chk_down.sh 
    sed -i '1i\#!/bin/bash' /etc/keepalived/chk_nginx.sh
    chmod +x "/etc/keepalived/*.sh"
    
    #配置nginx
    nginx -s stop
    mv /apps/nginx/conf.d/test.conf /apps/nginx/conf.d/test.conf.bak2
    mv /apps/nginx/conf/nginx.conf /apps/nginx/conf/nginx.conf.bak2
    cp /apps/nginx/conf/nginx.conf.bak /apps/nginx/conf/nginx.conf
    vim /apps/nginx/conf/nginx.conf
    http {
        upstream webs {
            server 192.168.37.37:80;
            server 192.168.37.47:80;
            least_conn;
        }
        server {
            listen       80;
            server_name  localhost;
            location / {
                root   html;
                index  index.html index.htm;
                proxy_pass webs;
        }
    }
        
    #启动服务
    nginx
    systemctl start keepalived
    scp "/etc/keepalived/*.sh root@192.168.37.27:/etc/keepalived/"
            
    #ka2
    #配置keepalived
    yum install keepalived -y
    yum install psmisc -y           #killall命令的安装包        
    vim /etc/keepalived/keepalived.conf
    global_defs {
       notification_email {
         admin@magedu.net       #发给本机root邮件
       }
       notification_email_from ka2@magedu.net
       smtp_server 127.0.0.1    #发邮件的地址
       smtp_connect_timeout 30
       router_id ka2        #主机名    
       vrrp_mcast_group4 224.0.0.100    #D类地址,多播
    }
    vrrp_script chk_down {      #自定义脚本
        script "/etc/keepalived/chk_down.sh"
        interval 1
        weight -30
    }
    vrrp_script chk_nginx {
        script "/etc/keepalived/chk_nginx.sh"
        interval 1
        weight -30
    }
    vrrp_instance VI_1 {    #虚拟路由器
        state BACKUP        #在另一个结点上为BACKUP
        interface eth0      #网卡接口
        virtual_router_id 10    #多个节点必须相同
        priority 80     #优先级,在另一个结点上要小于这个值
        advert_int 1        #通告间隔1s
        authentication {
            auth_type PASS  #预共享密钥认证
            auth_pass 123456    #密码
        }
        virtual_ipaddress {
            192.168.37.100/24 dev eth0 label eth0:1
        }
        track_script {      #引用脚本
            chk_down
            chk_nginx
        }
        notify_master "/etc/keepalived/notify.sh master"
        notify_backup "/etc/keepalived/notify.sh backup"
        notify_fault "/etc/keepalived/notify.sh fault"
    }
    
    #配置nginx
    vim /apps/nginx/conf/nginx.conf
    http {
        upstream webs {
            server 192.168.37.37:80;
            server 192.168.37.47:80;
            least_conn;
        }
        server {
            listen       80;
            server_name  localhost;
            location / {
                root   html;
                index  index.html index.htm;
                proxy_pass webs;
        }
    }
    #启动服务
    nginx
    systemctl start keepalived
            
    #client
    while true;do curl www.magedu.net;sleep 0.5;done
                
    #测试
    killall -9 nginx
    

    相关文章

      网友评论

          本文标题:nginx

          本文链接:https://www.haomeiwen.com/subject/dyyanhtx.html