返回首页

用 Nginx 反向代理 Node 服务

在 Linux 上把跑在其它端口的 Node 服务通过 Nginx 反向代理出去。

发布 2018年3月24日 标签 #linux #nginx #node

~/posts/nginx-node-service $ cat post.md

/ 语言 EN / 中文
/ 主题 / /

概览

把跑在其它端口的 Node 服务通过 Nginx 反向代理出去,连同安装步骤一起记一下。

安装

需要的几个工具:

  1. Nginx
  2. Node
  3. forever

Node

curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
sudo apt-get install -y nodejs

Nginx

sudo apt-get install -y nginx

forever

sudo npm install -g forever

配置

先看一下 Nginx 的全局配置。

全局配置

cd /etc/nginx
cat nginx.conf

文件大致是这样:

2018-07-19 更新:把 client_max_body_size 取消注释并调大,可以放宽上传文件的体积上限。

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off; # 2019-03-05 更新:关掉它能藏住 nginx 版本号,安全性略增

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    ##
    # Max POST upload size limit
    ##

    # client_max_body_size 20m;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;       # <== 确认未被注释
    include /etc/nginx/sites-enabled/*;     # <== 确认未被注释
}

确认 include /etc/nginx/conf.d/*.conf;include /etc/nginx/sites-enabled/*; 两行没被注释,被注释了就取消注释。

项目配置

/etc/nginx/conf.d,按习惯命名规则新建一个项目的配置文件。下面以给 champion-gg-bot 加官网 cgb.mipha.io 为例,Node 服务监听 8081

cd /etc/nginx/conf.d
sudo nano cgb_mipha_io_8081.conf

文件内容:

upstream cgbmiphaio {                   # 应用名
    server 127.0.0.1:8081;              # node 监听的端口
    keepalive 64;
}

server {
    listen 80;                          # 80 是 http,443 是 https
    server_name xxx.xxx.xxx.xxx cgb.mipha.io;  # 多个域名空格分隔

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_set_header Connection "";
        proxy_pass http://cgbmiphaio;   # 上面定义的应用名
    }
}

保存后 Nginx 不会自动加载,先校验配置再 reload:

sudo nginx -t
sudo service nginx reload
# 或第一次启动
sudo service nginx start

运行项目

build 完后,用 forever 把进程托管在后台:

forever start dist/index.js

查看 / 停止:

forever list
forever stop dist/index.js
forever stopall
返回首页