使用git作服務器端代碼的部署

傳統部署方案
     windows 遠程桌面
     FTP/SFTP
     登陸服務器pull github代碼
     Phing(PHP專業部署工具)

git 自動部署流程圖
     html

 



服務器端準備工做:
     0. 這些工做都在root或有管理權限的賬號下進行,下面以root爲用戶,切換到其餘用戶的時候會提示
     1. 確保安裝了git
     2. 爲了安全起見,新建一個專門用於代碼部署的無特權用戶
                useradd -m deployuser
                passwd deployuser #設置該用戶的密碼,也可根據喜愛配置成免密碼登錄
     3. 新建一個目錄做爲要部署代碼的根目錄,如:
                mkdir /var/www/html/deploy
     4. 將這個目錄的屬主和屬組都改成上面新建的用戶deployuser
                cd /var/www/html
                chown deployuser:deployuser deploy
     5. 切換到部署代碼的專用用戶
                su deployuser
     6. 進入項目根目錄,初始化爲git倉庫
                cd deploy
                git init
     7. 【重要】讓倉庫接受代碼提交
                git config receive.denyCurrentBranch ignore
                [可選] git config core.worktree ~/www
                [可選] git config --bool receive.denyNonFastForwards false #禁止強制推送
     至此,一個空的git倉庫就在服務器上建好了,倉庫的地址爲:
                ssh://deployuser@ipaddress/var/www/html/deploy/.git

本地倉庫準備工做:
     1. 經過 git clone 或 git pull 從 github 倉庫上將代碼獲取到本地
     2. 將服務器添加到遠程倉庫列表,使用名字來區分不一樣的服務器,如測試服務器能夠叫作testing
                git remote add testing ssh://deployuser@ipaddress/var/www/html/deploy/.git
     3. 將本地代碼提交到測試服務器上面
                git push testing master

回到服務器端:
    1. 更新服務端 git 倉庫狀態並檢出文件
                cd /var/www/html/deploy
                git update-server-info

                git checkout -f
        OR:
                git checkout branch_name # 若是push的不是master分支

    2. 檢查是否是將文件更新進來了
    3. 設置服務器端更新鉤子 post-update
              cd .git/hooks
       新建 post-receive 或將 post-receive.sample 重命名爲 post-receive
              touch post-receive
       OR:
              mv post-receive.sample post-receive
              vim post-receive
       將以下內容複製到文件中
                 #!/bin/sh
                 unset GIT_DIR
                 cd ..
                 git checkout -f
       注: 第3步的操做將post-receive 替換爲 post-update也能夠, 不過須要先將post-update中的exec git update-server-info這一行刪掉

後續代碼的更新:
     1. github 有更新的時候 pull 更新本地部署倉庫
     2. 而後本地先 push 到測試服務器進行測試
     3. 測試經過以後 push 到正式服務器進行上線
     4. 代碼的回滾:
               *服務器端回滾:推薦 git reset --hard HEAD^
               本地倉庫回滾: 無需登錄服務器便可實現代碼回滾,git reset HEAD^ 保留代碼回滾,而後使用 git push remote_name local_branch_name -f 強制推送

使用過程當中須要注意的問題:
     1. 須要約定好 git 不能更新的操做要怎麼處理,好比新增數據庫的字段,新安裝必要的擴...git

相關文章
相關標籤/搜索