git hooks deploy (nodejs)

deploy(部屬) 是個 production 的必經階段,該怎樣做的方便又穩定是個重要的關鍵,先來談談一般 web server deploy (以 nodejs 為例,這邊暫時不談 server side 架構)

(假設使用 bitbucket host git repo)

1. 把 local source code push (本地端原碼推到) bitbucket
2. ssh 連到 web server
3. git pull 想要的版本
4. npm install(更新 package)
5. restart node process (重起線程)

以上的步驟看起來其實也不難,ssh 連到 web server 的步驟也可以使用 key 的方式來減少輸入密碼步驟,進入後需要進行的東做也不是很難,但總是要問自己一下 "還能不能更好?",立馬想到先前使用些 saas 的經驗,如 heroku, openshift, nodejitsu ... 等,使用方式非常簡單,只需要把 code push 上 saas server,就自動可以跑起來,這種感覺真的太棒了!以 heroku 為例,會要求你在原本的 local repo 加入一個 remote 的位置(如下),之後想要 deploy 只要 `git push heroku master` 就可以丟上 heroku 並自動重起。
git add remote heroku GIT_REPO_URL

想要自己實作這段就必須使用 git hooks,以 bitbucket 為例(下圖),可在 repo 設定收到 push 後要執行哪些指令,bitbucket 很貼心的與很多不同的 service 合作,讓 hooks 更方便(一般常見的 git host 都有實作,不論是 github, gitlab...等都有)。


這段收到 push 後必須執行哪些指令的行為就是 git hookspost-receive,收到 push 後想要執行哪些指令,pust-receive 為 bash script,所以可以方變得跟各種 cmd 整合,基本上可以將最上面的步驟 3, 4, 5 整合,pull 想要的版本、更新package、重起 node process,但還是缺少了最重要的東西,git 要 push 到哪?

首先建立一個 git repo 並且使用 bare



接著更新 $HOME/deploy.git/hooks/post-receive(範例中使用 forever 來管理 node process,亦可使用 nodeman, pm2 等來管理)


最後就是在開發的 repo 中加入 remote 路徑,ssh user, ip 就與 ssh 登入是相同的
git remote add production SSH_USER@SSH_IP:~/deploy.git

完成後 deploy 就與 heroku, nodejitsu, openshift 一樣只要下指令就自動完成 deploy 所有流程(更新最新版 source code,更新 node package,重啟 nodejs process)
git push production master


相關連結
heroku
openshift
nodejitsu
bitbucket
github
gitlab
git hooks
forever
nodeman
pm2

nvm on ubuntu issue Syntax error: "(" unexpected (expecting ";;")

這幾天在處理 git hook 來 deploy 的問題卻一直遇到下面這段錯誤訊息

.nvm/nvm.sh: 502: .nvm/nvm.sh: Syntax error: "(" unexpected (expecting ";;")

查到後來才發現原來 ubuntu 6.10 起把預設的 bash shell 改為 dash shell,所以當你使用 /bin/sh 同時其實是使用 dash,要把 shell 改回 bash 使用以下指令:
sudo dpkg-reconfigure dash

輸入後會跳出以下畫面,選擇 no 就會把 shell 改為 bash


get ubuntu version

Get ubuntu version

lsb_release -a