小知识:用Nginx反向代理Node.js的方法

本文介绍了用Nginx反向代理Node.js的方法,分享给大家,具体如下:

安装pm2

?
1
2
3
npm install pm2 -g
ln -s /home/download/node-v8.11.1-linux-x64/lib/node_modules/pm2/bin/pm2 /usr/local/bin/pm2

修改package.json

?
1
2
3
4
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″,
“pm2”: “/home/download/node-v8.11.1-linux-x64/lib/node_modules/pm2/bin/pm2 start /web/mazey.cn/server/app.js”
}

or

?
1
2
3
4
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″,
“pm2”: “pm2 start app.js”
}

启动pm2

?
1
npm run pm2

开机启动pm2

?
1
2
3
pm2 save
pm2 startup centos

注意

若 pm2 startup centos 失败,可尝试 pm2 startup 。

?
1
2
3
PM2 detected systemv but you precised centos
Please verify that your choice is indeed your init system
If you arent sure, just run : pm2 startup

修改Nginx配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
vim /etc/nginx/conf.d/*.conf
upstream nodejs {
server 127.0.0.1:3000;
keepalive 64;
}
server {
listen 80;
server_name domain.cn;
root /web/mazey.cn;
index index.html index.htm;
# 网站切到/server下时走nodejs
location /server {
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://nodejs;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 1h;
}
}

相应的 app.js :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require(express)
const app = express()
let hi = hi
app.get(/server, (req, res, next) => {
hi = `Hello Mazey!\n`
next()
}, (req, res) => {
res.send(`
${hi}
${req.method}\n
${req.originalUrl}\n
${req.query.id}\n
`)
})
const server = app.listen(3000, function () {
let host = server.address().address
let port = server.address().port
console.log(Example app listening at http://%s:%s, host, port)
})

注意

若报错 Cannot GET /xxx 说明 Express 的路由没配好。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/aa38f106c630

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:本地HTTPS环境搭建的完整步骤记录

2023-4-19 1:04:40

建站知识

小知识:Nginx与浏览器缓存的处理方法

2023-4-19 1:23:05

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索