如何部署Nodejs服务
Favori,
图:Nguyen Nhut
服务器
阿里云 https://www.aliyun.com/daily-act/ecs/activity_selection
下载安装包
wget https://nodejs.org/dist/v10.9.0/node-v10.9.0-linux-x64.tar.xz
解压
tar xf node-v10.9.0-linux-x64.tar.xz
设置软链接
ln -s /root/node-v10.9.0-linux-x64/bin/node /usr/local/bin/node
ln -s /root/node-v10.9.0-linux-x64/bin/npm /usr/local/bin/npm`
查看Node版本和npm版本
node -v
npm -v
设置npm源
npm config set registry https://registry.npm.taobao.org
服务器安装pm2
npm install -g pm2
ln -s /root/node-v10.9.0-linux-x64/bin/pm2 /usr/local/bin/
配置ssh
- 本地生成秘钥对:
ssh-keygen -t rsa
demo_id_rsa - 将公钥放到服务器上:
scp ~/.ssh/demo_id_rsa.pub root@39.107.238.161:/root/.ssh/authorized_keys
- 修改ssh配置
vi ~/.ssh/config
Host john
HostName 39.107.238.161
User root
Port 22
IdentityFile ~/.ssh/demo_id_rsa
- 服务器上修改ssh配置
vim /etc/ssh/sshd_config
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys
- 最后就可以ssh登录了!
ssh john
将本地代码同步到服务器
rsync -avzp -e "ssh" ./Internet/ john:/root/app
服务器上启动http
pm2 start /root/app/http-server.js
本地修改发布命令
新建deploy.sh文件
#!/bin/bash
HOST=john
rsync -avzp -e "ssh" ./Internet/ $HOST:/root/app
ssh $HOST "pm2 restart /root/app/http-server.js"
echo 'deploy success'
初始化npm命令
npm init
新增scripts "deploy": "./deploy.sh"
发布
npm run deploy
修改http-server的监听host
const http = require('http')
const host = '0.0.0.0';
const port = 80;
http.createServer(function (req, res) {
res.writeHead(## {
'Content-Type': 'text/plain'
})
res.end('Hello World')
}).listen(port, host)
console.log(`Server running at http://${host}:${port}/`)
ECS安全组添加80端口
查看服务器上是否已正常监听80端口
netstat -tpln
通过ip+端口访问
39.107.238.161:80