原理:本地git倉庫與遠程倉庫關聯(github、碼雲等平臺),而後pm2按照指定配置登陸服務器,拉取遠程倉庫的代碼更新。git
npm install pm2@latest -g
複製代碼
git init
github
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木做爲靜態文件目錄ajax
建立好的倉庫地址:express
git@github.com:cooleye/daviesite.git
複製代碼
git remote add origin git@github.com:cooleye/daviesite.git
複製代碼
pm2 ecosystem
複製代碼
運行命令的當前目錄下會生成一個ecosystem.json 文件 編輯ecosystem.json:npm
{
"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"
}
}
}
複製代碼
npm install pm2@latest -g
複製代碼
在服務器端生成 ssh公鑰和私鑰json
ssh-keygen -t rsa -C "youremail"
複製代碼
cat ~/.ssh/id_rsa.pub
複製代碼
/mnt/daviesite
目錄上,查看是否有寫入的權限,沒有的話須要添加寫入權限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運行bash
pm2 deploy ecosystem.json production
複製代碼
執行這一步,服務器會依照 package.json 安裝依賴服務器
pm2 deploy production update
複製代碼
更新代碼app
實際在使用中,發現更新不成功,可是服務端執行這句是能夠的,可是我並不想在服務端執行,我須要在本地就能夠直接更新。 辦法是,修改ecosystem.jsonssh
"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
複製代碼