8
部署Nodejs服务器并绑定域名
source link: https://www.fengxianqi.com/index.php/archives/20/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
部署Nodejs服务器并绑定域名
学习node的时候一直都是在本地通过
http://localhost:3000
访问就行了,但如何在服务器上运行node并且通过公网域名访问?接下来尝试通过nginx反向代理搭建node服务器,并且不影响服务器上其他网站。
准备工作:
- 服务器:Centos7.2
- 服务器已安装node
- 服务器已安装Nginx
- 把域名
node.fengxianqi.com
解析到服务器ip
- 访问
node.fengxianqi.com
,输出hello word!
配置步骤:
- 配置Nginx,使得访问
node.fengxianqi.com
时候转到http://localhost:3000
处理请求,配置文件如下:
server {
listen 80;
server_name node.fengxianqi.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
配置后重启Nginx,service nginx restart
。
- 在服务器网站目录下(如:
/www/node/
),建立项目文件,这里为了简单直接写一个app.js
文件就行:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`服务器运行在 http://${hostname}:${port}/`);
});
- 运行
app.js
。通常我们学习时是直接node app.js
这样执行的,但在服务器上这样做的话,一退出服务器运行就停止了,所以要装forever
让程序保持运行:
sudo npm -g install forever
开启进程:
forever start /path/app.js
查看所有进程:
forever list
关闭所有进程:
forever stopall
- 启动后我们通过浏览器访问
node.fengxianqi.com
就行了。
「一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!」
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK