原理:本地git仓库与远程仓库关联(github、码云等平台),然后pm2按照指定配置登录服务器,拉取远程仓库的代码更新。
npm install pm2@latest -g
git init
let express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
var proxy = require('http-proxy-middleware');
app.use('/ajax', proxy({
target: "http://m.maoyan.com/",
changeOrigin: true
}));
app.listen(3000,function(){
console.log('server start@127.0.0.1:3000')
})
使用 app.use(express.static(path.join(__dirname, 'public')));
把public木作为静态文件目录
创建好的仓库地址:
git@github.com:cooleye/daviesite.git
git remote add origin git@github.com:cooleye/daviesite.git
pm2 ecosystem
运行命令的当前目录下会生成一个ecosystem.json 文件 编辑ecosystem.json:
{
"apps":[
{
"name": "daviesite",
"script": "index.js",
"env": {
"COMMON_VARIABLE": "true"
},
"env_production": {
"NODE_ENV": "production"
}
}
],
"deploy": {
"production": {
"user":"root",
"host": ["47.108.78.24"],
"port": "22",
"ref": "origin/master",
"repo": "git@github.com:cooleye/daviesite.git",
"path": "/mnt/daviesite",
"ssh_options": "StrictHostKeyChecking=no",
"pre-setup": "echo 'This is a pre-setup command'",
"post-setup": "ls -la",
"pre-deploy-local": "echo 'This is a pre-deploy-local command'",
"post-deploy" : "npm install && pm2 start 0"
}
}
}
- user :登录用户名
- host : 要部署的目标服务器或者域名
- ref : 用于部署代码时的分支
- repo : git 仓库地址
- path : 在目标服务器上部署的文件目录地址
- post-deploy : 部署后启动的脚本
npm install pm2@latest -g
在服务器端生成 ssh公钥和私钥
ssh-keygen -t rsa -C "youremail"
cat ~/.ssh/id_rsa.pub
git add .
git commit -m 'update'
git push origin master
scp ~/.ssh/id_rsa.pub root@47.98.154.75:/root/.ssh/authorized_keys
pm2 deploy ecosystem.json production setup
执行这一步,服务器会会github上clone代码下来,并使用pm2运行
pm2 deploy ecosystem.json production
执行这一步,服务器会依照 package.json 安装依赖
pm2 deploy production update
更新代码
实际在使用中,发现更新不成功,但是服务端执行这句是可以的,但是我并不想在服务端执行,我需要在本地就可以直接更新。 办法是,修改ecosystem.json
"post-deploy" : "git pull origin master && npm install && pm2 start 0"
在执行 pm2 deploy ecosystem.json production
的时候,会从github下载更新
pm2 deploy production revert 1
pm2 deploy production --force
修改package.json配置文件,添加命令:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "pm2 start index.js",
"sp": "pm2 deploy ecosystem.json production setup",
"dp": "pm2 deploy ecosystem.json production",
"ud": "pm2 deploy production update",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"http-proxy-middleware": "^0.19.1"
}
}
这样,以后安装部署就执行
npm run sp
更新部署就执行:
npm run dp