安裝git服務器
先安裝依賴軟件:yum -y install gcc zlib-devel openssl-devel perl cpio expat-devel gettext-devel openssl zlib curl autoconf tk
一、下載最新的git文件:https://www.kernel.org/pub/software/scm/git/git-2.13.0.tar.gz
二、tar xzf git-2.11.1.tar.gz
三、cd git-2.11.1
四、./configure --prefix=/usr/local
五、make && make install
六、git version 查看版本,完工。php
配置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 restartgit
建立倉庫
cd /home
mkdir gitrepos
cd gitrepo
git init --bare test.git
記得把倉庫所屬用戶改成git chown -R git:git test.git
git clone git@ip地址:test.git的絕對路徑 拉取github
網上不少說須要禁止git用戶shell登陸,發現操做後證書也就沒法訪問了,因此必定不要禁用這個。web
正確的應該是git:x:1001:1001:,,,:/home/git:/bin/bash這樣shell
你用hook鉤子自動部署代碼vim
1.進入到項目下的hooks目錄 cd /home/git/test.git/hooks/bash
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.給鉤子可執行權限和所屬用戶和用戶組ssh
chmod +x post-receive
chown git:git post-receive
4.給git用戶生成ssh證書並加入到git的authorized_keyscurl
5.須要項目目錄777權限,若是提示error: cannot open .git/FETCH_HEAD: Permission denied錯誤,須要設置項目下.git/FETCH_HEAD文件用戶和用戶組爲git
使用webhooks自動更新代碼
不少時候咱們代碼託管在github或其餘地方,更新代碼時每次都須要去服務器上git pull,很不方便,這時候咱們就可使用webhooks來更新代碼
一、建立一個文件webhooks.php,這個文件須要能url訪問http://test.com/webhooks.php
二、在文件裏面加入如下代碼
<?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); ?>
三、切換到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就能夠了