將 Github 的 Hugo 專案移到 Linode (3) - 將 Linode 設為 Git Server
目標
在本地開發完成後,只要輸入 git push
,Linode 就會自動幫我:
- 把程式碼推到
/var/www/abc.com/
- 執行
hugo
,更新靜態檔案 - 在瀏覽器輸入 Linode IP,會看到新的內容
流程介紹
- 在 Linode 建立接收站,用來接收
git push
的內容 - 把接收站設為實際 repo 的遠端連結
- 設定接收站的部署流程
- 把此專案下載到本地,推送新的內容
- 在瀏覽器輸入 Linode 主機 IP,看到網站最新內容
實際操作
1. 在 Linode 建立接收站,用來接收 git push
的內容
mkdir -p /opt/git/abc-com.git
cd /opt/git/abc-com.git
git init --bare
Bare Repository,直接翻譯成中文叫「裸倉庫」,但我覺得很難理解,所以把它叫做「接收站」。
為什麼需要設定接收站?
- 不要讓實體的
/var/www/abc.com
直接當作 Git 的接收站,可能有風險,所以開設一個「接收站」。裡面沒有實際程式碼內容,只是用來接收 Git 的 commit、分支等資料。 - 目的是用來接收你的
git push
。
2. 把接收站設為實際 repo 的遠端連結
接收站推薦擺放位置在:/opt/git/
資料夾裡面:
cd /var/www/abc.com # 實際 repo 位置
git remote set-url origin /opt/git/abc-com.git
git push origin master # 把 git commit 記錄推一份到接收站
3. 設定接收站的部署流程
接收站的部署設定檔,叫 post-receive
,通常會放在該 Git 專案裡面的 .git/hooks/post-receive
,以這篇的例子是 /opt/git/abc-com.git/hooks/post-receive
。
cd /opt/git/abc-com.git/hooks
vim post-receive
post-receive
內容如下:
#!/bin/bash
echo "=== [Post-Receive Hook] Deploying site ==="
TARGET="/var/www/abc.com"
GIT_WORK_TREE="$TARGET" git checkout -f # 把這次 commit 的實體內容推到 $TARGET
cd "$TARGET"
hugo # 執行完會把靜態資料更新到 var/www/abc.com/public
echo "=== Deployment done ==="
儲存後,給這個檔案執行權限:
chmod +x post-receive # change mode
4. 把此專案下載到本地,推送新的內容
回到本地的終端機,執行:
git clone ssh://root@192.xx.xx.xx:/opt/git/abc-com.git
此時會把整個專案下載到本地。
接著,在本地隨便修改一些內容後,執行:
git add .
git commit -m "test commit"
git push origin master
5. 測試
在瀏覽器打開 http://192.xx.xx.xx
,看到最新的網站內容。