首先簡單說下思路:本地git倉庫與遠程倉庫關聯(github、碼雲等平臺),而後pm2按照指定配置登陸服務器,拉取遠程倉庫的代碼更新,再執行一些指定的命令(如打包等)。javascript
app.js
,mkdir web && cd web vi app.js
文件內容編輯以下,完成後保存退出:wq!
。css
// app.s const http = require('http'); const homePage = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style type="text/css"> * { padding: 0; margin: 0; } body { padding: 30px 0; text-align: center; font-size: 16px; background-color: #333; } h1,h2 { color: #fff; } nav { margin-top: 20px; } a { color: #ccc; cursor: pointer; } a:hover { text-decoration: underline; } </style> </head> <body> <h1>Nodejs部署示例項目</h1> <h2>項目部署上線示例</h2> <nav> <ul> <li><a>列表</a></li> </ul> </nav> </body> </html> ` http.createServer((req,res) => { res.statusCode = 200; res.setHeader('Content-Type','text/html'); res.end(homePage); }).listen(3000, () => { console.log('Sever Running On 3000:'); })
.ssh
目錄及目錄下是否有私鑰及公鑰文件ls ~/.ssh
id_rsa
、id_rsa.pub
文件,須要先生成一下:"youemail"填寫你的郵箱
ssh-keygen -t rsa -C "youremail"
cat ~/.ssh/id_rsa.pub
服務器環境:阿里雲的ecs,系統是Ubuntu 14.06
這一步後面是不須要手動操做的,但咱們要作好配置,這裏能夠先手動拉取遠程代碼測試一下是否配置成功。html
xxxx爲你遠程倉庫的項目地址
cd ~ git clone xxxx
在本地項目中新建配置文件ecosystem.json
,這裏爲了方便理解添加了註釋,但json文件不能有註釋,記得去掉。java
{ "apps":[ { "name": "website", // 項目名稱 "script": "app.js", // 入口文件 "env": { "COMMON_VARIABLE": "true" }, "env_production": { "NODE_ENV": "production" // 環境變量 } } ], // 環境部署的配置,此處只以production爲例 "deploy": { "production": { // 登陸服務器的用戶名 "user":"slevin", // 服務器ip "host": ["47.75.191.199"], // 服務器ssh登陸端口,未修改的話通常默認爲22 "port": "22", // 指定拉取的分支 "ref": "origin/master", // 遠程倉庫地址 "repo": "git@gitee.com:mslevin/website.git", // 指定代碼拉取到服務器的目錄 "path": "/www/website/production", "ssh_options": "StrictHostKeyChecking=no", "env": { "NODE_ENV": "production" } } } }
/www/website/production
,但可能並不存在,須要手動新建:mkdir /www && cd www mkdir website
因爲pm2須要在website
目錄中建立productions
目錄,須要更改website
的讀寫權限nginx
cd /www sudo chmod 777 website
.bashrc
文件,下面幾行都註釋掉這步是爲了防止部署的時候服務器報錯找不到pm2命令
# If not running interactively, don't do anything #case $- in # *i*) ;; # *) return;; #esac
pm2 deploy ecosystem.json production setup pm2 deploy ecosystem.json production
若是沒有問題的話,本地打開瀏覽器訪問對應ip:port就能夠看到內容了。
後面每次項目作了個更新以後, 同步到遠程倉庫,而後執行pm2 deploy ecosystem.json production
便可。git