首先简单说下思路:本地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