安裝git服務器
先安裝依賴軟件:yum -y install gcc zlib-devel openssl-devel perl cpio expat-devel gettext-devel openssl zlib curl autoconf tk
1、下載最新的git文件:https://www.kernel.org/pub/software/scm/git/git-2.13.0.tar.gz
2、tar xzf git-2.11.1.tar.gz
3、cd git-2.11.1
4、./configure --prefix=/usr/local
5、make && make install
6、git version 查看版本,完工。
配置git證書登錄
1.添加個一個git用戶
groupadd git
adduser git -g git
passwd git 修改密碼
2.拷貝本地公匙文件到服務器
scp /Users/wanghui/.ssh/id_rsa.pub git@118.178.138.113:~/
3.導入公匙到服務器
使用git賬號登錄,查看/home/git目錄下是否有.ssh目錄,沒有就新建
mkdir ~/.ssh
chmod 700 ~/.ssh
touch .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
將剛才上傳到服務端的id_rsa.pub文件中的內容添加到目錄/.ssh/authorized_keys中, 刪除剛才上傳到服務端的的id_rsa.pub
cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
rm ~/id_rsa.pub
然后就可以使用證書登錄了
如果以上步驟不能實現不輸密碼登陸的話,需要檢查sshd服務的Pubkey認證功能是否默認打開
修改/etc/ssh/sshd_config, 改以下條目
PubkeyAuthentication yes 修改后需要重啟ssh service sshd restart
創建倉庫
cd /home
mkdir gitrepos
cd gitrepo
git init --bare test.git
記得把倉庫所屬用戶改為git chown -R git:git test.git
git clone git@ip地址:test.git的絕對路徑 拉取
網上很多說需要禁止git用戶shell登錄,發現操作后證書也就無法訪問了,所以一定不要禁用這個。
正確的應該是git:x:1001:1001:,,,:/home/git:/bin/bash這樣
你用hook鈎子自動部署代碼
1.進入到項目下的hooks目錄 cd /home/git/test.git/hooks/
2.添加post-receive文件然后編輯 vim post-receive 插入以下代碼
#!/bin/sh unset GIT_DIR NowPath=`pwd` DeployPath="/data0/web/www/" cd $DeployPath git pull origin master cd $NowPath exit 0
3.給鈎子可執行權限和所屬用戶和用戶組
chmod +x post-receive
chown git:git post-receive
4.給git用戶生成ssh證書並加入到git的authorized_keys
5.需要項目目錄777權限,如果提示error: cannot open .git/FETCH_HEAD: Permission denied錯誤,需要設置項目下.git/FETCH_HEAD文件用戶和用戶組為git
使用webhooks自動更新代碼
很多時候我們代碼托管在github或其他地方,更新代碼時每次都需要去服務器上git pull,很不方便,這時候我們就可以使用webhooks來更新代碼
1、創建一個文件webhooks.php,這個文件需要能url訪問http://test.com/webhooks.php
2、在文件里面加入以下代碼
<?php // 獲取push數據內容的方法 #$requestBody = file_get_contents("php://input"); //echo exec("id -a");//查看web運行的用戶 // 只需這一行代碼便可拉取,使用 2>&1,命令就會輸出shell執行時的錯誤到$log變量, 輸出該變量即可分析。 exec('cd /home/wwwroot/test/ && git pull 2>&1',$log,$status); //print_r($log); ?>
3、切換到web運行賬號su www,生成ssh key,把key加入到git管理,然后git clone 拉取代碼。(切記不能使用root等其他賬號拉取代碼)
提示www This account is currently not available.解決辦法
more /etc/passwd查看賬號信息,發現www的shell是“/sbin/nologin”,所以需要將起改成“/bin/bash”
訪問http://test.com/webhooks.php 查看能否運行成功,成功后把地址放到github的webhooks就可以了