美文网首页
node反向代理与负载均衡

node反向代理与负载均衡

作者: zxhnext | 来源:发表于2019-03-25 17:50 被阅读0次

    一、node如何应对高并发

    1. 增加每台机器的cpu数--多核
    2. 反向代理
    3. 负载均衡

    二、进程与线程

    1. 进程:是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位
    2. 多进程:启动多个进程,多个进程可以一块执行多个任务
    3. 线程:进程内一个相对独立的,可调度的执行单元,与同属一个进程的线程共享进程的资源
    4. 多线程:启动一个进程,在一个进程内启动多个线程,这样,多个线程也可以一块执行多任务

    三、反向代理

    反向代理(Reverse Proxy)方式是指以代理服务器来接受Internet上的连接请求,然后将请求转发给内部网络上的服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器对外就表现为一个服务器。
    这里我们使用nginx,下面我们来讲下具体的nginx配置,如下是nginx初始文件

    #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 {
        worker_connections  1024;
    }
    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;
        #gzip on;
        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
        #
        #server {
        #    listen   443 ssl;
        #    index  index.html index.htm;          
        #    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. 全局块: 配置影响nginx全局的指令,一般由运行nginx的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。
    2. events块: 配置影响nginx服务器或与用户的网络连接。有每个进程的足大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网络连接,开启多个网络连接序列化等。
    3. http块: 可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。
    4. server块: 配置虚拟主机的相关参数,一个http中可以有多个server。
    5. location块: 配置请求的路由,以及各种页面的处理情况。
    ...
    events { ...
    }
    http
    # #events
    #http
    {
    ... #http server #server {
    ... #server
            location [PATTERN]
            {
    ... }
            location [PATTERN]
            {
    ... }
    }
    server
    { ...
    }
    ... #http }
    #location
    

    先来简单介绍下我们常用的配置项

    #user  nobody; // 以什么用户身份启动
    worker_processes  1; // 工作进程数,默认为1
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    
    #pid        logs/nginx.pid; // 进程管理
    
    events {
        worker_connections  1024; // 最大连接数
    }
    
    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; // 长连接超时时间
    
        #gzip  on; // 是否压缩
    
        server { // 虚拟站点
            listen       8080;
            server_name  localhost; // 主机名
    
            #charset koi8-r; // 默认字符集,不用管,非要改就改为utf-8
    
            #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;
            }
        }
    }
    

    nginx如何在一个服务器上配置两个项目,并通过两个不同的域名访问

    server {
           listen       80;
           server_name example.com;
           index index.html index.htm index.php default.html default.htm default.php;
           root  /home/am/webapps/am;
    
           location / {
               proxy_pass http://test.horace.space:8080/am/;
           }
           error_page   500 502 503 504  /50x.html;
           location = /50x.html {
               root   html;
           }
    }
    
    server {
           listen       80;
           server_name example.com;
           index index.html index.htm index.php default.html default.htm default.php;
           root  /home/tq/webapps/tq;
    
           location / {
               proxy_pass http://m.horace.space:8089/tq/;
           }
           error_page   500 502 503 504  /50x.html;
           location = /50x.html {
               root   html;
           }
    }
    

    在这里做一下解释:

    1. listen 监听80端口
    2. server_name 项目所对应的域名
    3. index 项目首页名称
    4. root 项目存放路径
    5. proxy_pass 域名对应URL,这个URL对应的就是http://m.horace.space,可通过域名直接访问
    6. 如果你想配置多个项目只需要将service{}复制多份即可。
      如果你觉得把所有配置都写在nginx.conf中很乱,我们可以在conf.d文件夹中对每个项目单独配置,比如我们先建一个zxhnext-3001.conf,内容如下:
    upstream hapi-demo {
        server 127.0.0.1:3001;
    }
    
    server {
        listen 80;
        server_name www.zxhnext.cn;
    
        location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_pass http://hapi-demo;
        proxy_redirect off;
        }
    }
    

    然后我们只需要在nginx.conf中把conf.d文件夹中的文件全部引入即可

    include /etc/nginx/conf.d/*.conf;
    

    如果我们需要做负载均衡,则可以这样:

    upstream firsttest { // 服务器名字,代理到什么地方
        ip_hash; // 落到某台机器上就不会改变了
        server 192.168.0.21;   weight=2; // 权重,出现几率为2/3
        server 192.168.0.31;
    }
    server {
      listen 8080;
      location / {
          proxy_pass http://firsttest; // 访问根地址时代理到http://firsttest
      }
    }
    

    upstream 后面是自己起的名字,如果要做负载,可以多写几个server服务器地址,可以自动切换
    ip_hash保证用户刷新时还落到原来访问的服务器上
    server指定服务器的权重 默认1:1:1

    最后再来看下nginx相关的基础操作

    nginx # 开启nginx
    nginx -s stop # 关掉nginx
    nginx -s reload # 重载nginx
    nginx -t # 检查nginx配置是否有误
    server_tokens off;  # 在nginx.conf中加上这句,去掉nginx版本信息
    

    四、进程守护

    pm2配置:

    {
      "apps:": [
        {
          "name": "hapi-demo", // 项目名
          "script": "app.js", // 执行文件
          "env": {
            "COMMON_VARIABLE": true,
          },
          "env_production": {
            "NODE_ENV": "production"
          }
        }
      ],
      "deploy": {
        "production": { // 随意起名
          "user": "root", // 哪个用户
          "host": ["140.143.15.124"], // 主机地址
          "port": "39999", // 端口
          "ref": "origin/master", // 哪个分支
          "repo": "git@gitee.com:zxhnext/hapi-demo.git", // 代码仓库地址
          "path": "/www/hapi-demo/production", // 服务器存放代码地址
          "ssh_options": "StrictHostKeyChecking=no", // 取消key校验
          "env": {
            "NODE_ENV": "production"
          }
        }
      }
    }
    

    参考官网配置:http://pm2.keymetrics.io/docs/usage/deployment/

    pm2常用命令

    $ pm2 start app.js              # 启动app.js应用程序
    
    $ pm2 start app.js -i 4         # cluster mode 模式启动4个app.js的应用实例     # 4个应用程序会自动进行负载均衡
    
    $ pm2 start app.js --name="api" # 启动应用程序并命名为 "api"
    
    $ pm2 start app.js --watch      # 当文件变化时自动重启应用
    
    $ pm2 start script.sh           # 启动 bash 脚本
    
    
    $ pm2 list                      # 列表 PM2 启动的所有的应用程序
    
    $ pm2 monit                     # 显示每个应用程序的CPU和内存占用情况
    
    $ pm2 show [app-name]           # 显示应用程序的所有信息
    
    
    $ pm2 logs                      # 显示所有应用程序的日志
    
    $ pm2 logs [app-name]           # 显示指定应用程序的日志
    
    $ pm2 flush
    
    
    $ pm2 stop all                  # 停止所有的应用程序
    
    $ pm2 stop 0                    # 停止 id为 0的指定应用程序
    
    $ pm2 restart all               # 重启所有应用
    
    $ pm2 reload all                # 重启 cluster mode下的所有应用
    
    $ pm2 gracefulReload all        # Graceful reload all apps in cluster mode
    
    $ pm2 delete all                # 关闭并删除所有应用
    
    $ pm2 delete 0                  # 删除指定应用 id 0
    
    $ pm2 scale api 10              # 把名字叫api的应用扩展到10个实例
    
    $ pm2 reset [app-name]          # 重置重启数量
    
    
    $ pm2 startup                   # 创建开机自启动命令
    
    $ pm2 save                      # 保存当前应用列表
    
    $ pm2 resurrect                 # 重新加载保存的应用列表
    

    相关文章

      网友评论

          本文标题:node反向代理与负载均衡

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