目的
有一台阿里云服务器和自己的域名(jackyang.me),想要在服务器上部署多个node express应用:blog和game。但是又不希望在访问时通过端口号来区分不同的应用(例如:jackyang.me:3000为blog应用,jackyang.me:3001为game应用)。那么就可以使用nginx来完成,访问时都通过默认的80端口,根据域名的不同,在nginx里转发到各自的应用中去。
安装nginx
Please google it.运行一下,在浏览器中输入jackyang.me,如果看到这个画面,你就装好了。
sudo /usr/local/nginx/sbin/nginx
welcome to nginx!
创建blog应用的配置文件
sudo mkdir /etc/nginx/jackyang.mesudo touch /etc/nginx/jackyang.me/blog.conf
其配置文件内容如下:
# upstream name is blog.jackyang.me # and my blog express app is running under port 3000 upstream blog.jackyang.me { server 127.0.0.1:3000; keepalive 8; } # the nginx server instance server { listen 0.0.0.0:80; server_name blog.jackyang.me; 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; # value for proxy_pass has to match upstream name proxy_pass http://blog.jackyang.me/; proxy_redirect off; } }
创建game应用的配置文件
sudo touch /etc/nginx/jackyang.me/game.conf
其配置文件内容如下:
# upstream name is blog.jackyang.me # and my blog express app is running under port 3000 upstream game.jackyang.me { server 127.0.0.1:3001; keepalive 8; } # the nginx server instance server { listen 0.0.0.0:80; server_name game.jackyang.me; 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; # value for proxy_pass has to match upstream name proxy_pass http://game.jackyang.me/; proxy_redirect off; } }
修改nginx配置
下面需要在nginx的启动配置中引入上面创建的两个配置文件:
sudo vi /usr/local/nginx/conf/nginx.conf
在http块中添加一条include语句即可:
...http { ... include /etc/nginx/jackyang.me/*.conf; ... }...
启动nginx
sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
启动blog和game应用
这里需要提前装node的forever,以免terminal退出后服务器进程就停掉了。并且要按照上面配置的,blog运行在3000端口,game运行在3001端口上。
forever start /var/www/jackyang.me/blog/server.js forever start /var/www/jackyang.me/game/server.js
配置域名解析
本文由傻鸟发布,不代表傻鸟立场,转载联系作者并注明出处:https://shaniao.net/jishu/29.html