建立 Git 伺服器並同步到指定目錄

📢 本文由 gemini-2.5-flash 翻譯

引言

使用 Git 可以更好地和朋友一起管理程式碼,也方便同步程式碼。由於我比較喜歡靜態網站,因此使用 Git 同步網頁檔案非常實用。

安裝 Git

登入 ROOT 帳號,依序輸入以下指令

1
2
yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel
yum install git

建立使用者

建立一個 Git 使用者群組和使用者,用於執行 Git 服務

1
2
groupadd git
useradd git -g git

公開金鑰獲取

此部分為自己電腦的公開金鑰,以 Windows 為例

%UserProfile%/.ssh/ 目錄下 id_rsa.pub 檔案儲存

如果沒有此檔案,開啟 cmd 執行 ssh-keygen 指令會自動產生

匯入公開金鑰

將待匯入的公開金鑰匯入 /home/git/.ssh/authorized_keys 檔案中,一行一個。如果沒有該檔案,則建立一個

1
2
3
4
5
cd /home/git/
mkdir .ssh
chmod 755 .ssh
touch .ssh/authorized_keys
chmod 644 .ssh/authorized_keys

然後使用 vi 或 vim 指令將公開金鑰匯入,使用參考: vim 文字編輯

初始化 Git 儲存庫

選定一個目錄作為 Git 儲存庫,假設為 /home/gitrepo/repo.git

1
2
3
4
5
cd /home
mkdir gitrepo
chown git:git gitrepo
cd gitrepo
git init --bare repo.git

以上指令 Git 會建立一個空儲存庫,伺服器上的 Git 儲存庫通常都以 .git 結尾。然後,將儲存庫所屬使用者改為 git:

1
chown -R git:git runoob.git

克隆儲存庫

1
2
3
git clone git@您的IP:倉庫目錄
// 例如
git clone [email protected]:/home/gitrepo/repo.git

同步目錄

自動同步功能用到的是 Git 的掛鉤 (hook) 功能

進入儲存庫目錄 /home/gitrepo/repo.git

1
2
cd /home/gitrepo/repo.git
cd hooks

建立並編輯檔案 post-receive

1
vi post-receive

在該檔案寫入以下內容

1
2
#!/bin/sh
git --work-tree=同步到的目錄 --git-dir=倉庫位置 checkout -f

例如

1
2
#!/bin/sh
git --work-tree=/home/www/hexo --git-dir=/home/gitrepo/repo.git checkout -f

然後設定該檔案讀寫權限

1
chmod +x post-receive

改變 repo.git 目錄的擁有者為 git 使用者

1
chown -R git:git /home/gitrepo/repo.git

更新程式碼

如果你能確定什麼都沒有改動過只是更新本地程式碼,直接使用

1
git pull

正規流程

1
2
3
4
5
6
7
8
9
// 查看本地分支檔案資訊,確保更新時不產生衝突
git status
// 如果檔案有修改,可以還原到最初狀態; 如果檔案需要更新到伺服器上,應該先合併 (merge) 到伺服器,再更新到本地
git checkout – [file name]
// 查看目前分支情況
git branch
// 如果分支為本地分支,則需切換到伺服器的遠端分支
git checkout remote branch
git pull

其他指令

1
2
3
4
git branch // 看看分支
git checkout aaa // 切換分支aaa
git branck aaa // 建立aaa分支
git chechout -b aaa // 本地建立 aaa分支,同時切換到aaa分支。只有提交的時候才會在伺服器上建立一個分支

禁用 git 使用者的 shell 登入權限

出於安全考量,我們要讓 git 使用者不能透過 shell 登入。可以編輯 /etc/passwd 來實現

1
vi /etc/passwd

1
git:x:1004:1004::/home/git:/bin/bash

改為

1
git:x:1004:1004::/home/git:/usr/bin/git-shell

這樣 git 使用者可以透過 ssh 正常使用 git,但是無法登入 sehll

參考文章

Linux chown 指令-菜鳥教學

Git 伺服器建置-菜鳥教學

Git - 產生 SSH 公開金鑰

SSH key 的介紹與在 Git 中的使用 - 簡書

Git - 在伺服器上建置 Git

git 更新程式碼到本地_ftToday 的部落格-CSDN 部落格

如何在伺服器上建置 hexo 部落格-阿里云開發者社群

Linux 權限詳解(chmod、600、644、700、711、755、777、4755、6755、7755)_林20 的部落格-CSDN 部落格

詳細解析 Linux /etc/passwd 檔案 - Jtianlin - 部落格園

This post is licensed under CC BY-NC-SA 4.0 by the author.