使用Git自動更新實現本地一鍵推送到正式服務器項目中


git有個hooks功能,每次push提交代碼的時候,可以觸發遠程服務器上的hooks,執行shell。 利用這個功能,每次在本地寫好內容,直接push到遠程服務器上,就可以根據寫好的shel自動部署了。用起來相當方便,下面就記錄下配置過程:

一、在遠程服務器上創建代碼倉庫(Linux)

# mkdir -p /home/www/project.git
# chmod 777 /home/www
# cd /home/www/project.git
# git init --bare             //創建一個裸倉庫
# useradd -s /bin/bash git   //因為需要執行shell,把shell指定成/usr/bin/git-shell 或/sbin/nogin 無法使用git hooks來更新blog
# chown git:git -R /home/www/project.git

 

二、配置本地無密碼登錄遠程服務器(win)

# ssh-keygen // 一路回車 然后復制生成的key(當前用戶下的.ssh/id_rsa.pub) 

切換到Linux

# mkdir -p /home/git/.ssh
# vim /home/git/.ssh/authorized_keys  //把上面復制的key粘貼進去,后保存退出
# chown git:git -R /home/git/.ssh
# chmod 600 /home/git/.ssh/authorized_keys //權限不要出錯
# chmod 755 /home/git/.ssh

  

三、本地初始化git,並且添加遠程倉庫(win)

# d:                    //進入D盤
# mkdir -p project
# cd project
# git init
# git config user.email "wzp@qq.com"
# git config user.name "wzp"
# echo "1111" > 1.txt
# git add 1.txt
# git commit -m "add 1.txt"
# git remote add blog ssh://git@127.0.0.1:22/home/www/project.git   //添加遠程倉庫還沒有提交過,所以要先提交一次. 注意ssh后面有://
# git push blog master   //提交到主干
git remote add <分支名> <遠程地址>  //上面的blog 就是分支,這個可以隨便自定義
如果git remote add 加錯了,可以使用 git remote rm <分支名> 來刪掉:
# git remote rm blog
//以后使用這個克隆就行了
//git clone ssh://git@127.0.0.1:22/home/www/project  
//ssh協議,后面是 用戶@地址:端口/目錄

  

四、添加hooks

# cd /home/www/project.git/hooks
# vim post-receive
#!/bin/sh
#

PATH=$PATH:/usr/local/python27/bin
GIT_WORK_TREE=/home/www/newproject git checkout -f
cd /home/www/newproject && make html >/dev/null 2>&1

chmod +x post-receive
chown git:git -R /home/www/newproject 
注意:寫hooks的時候要特別注意環境變量問題。

  

錯誤記錄:

文件沖突

# git push blog master
> error: failed to push some refs to 'ssh://git@127.0.0.1/home/www/project'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again.  See the 'Note about
fast-forwards' section of 'git push --help' for details.

 

這個是因為你本地的代碼和git遠程倉庫的代碼出現了沖突 解決辦法:
1.先把遠程文件拉下來,再push

# git config branch.master.remote blog
# git config branch.master.merge refs/heads/master
# git pull blog master
# git push blog master

 

2.強制更新

# git push -f blog master  
//注意,會覆蓋遠程倉庫上的文件,慎用

  

以上步驟就能解決了。

再來說說如果服務器上已經有項目的話如何快速git到本地,首先進入Liunx中項目根目錄把項目拉取到服務器git倉庫

# cd /home/wwwroot/newproject  //進入項目目錄
# git init
# git add .
# git config  user.email "test@qq.com"
# git config user.name "test"
# git commit -m "first up"
# git status
# git remote add tests git@127.0.0.1:22/home/www/project.git
# git push tests master

  

服務器git倉庫拉取完成之后再在win用git工具把項目拉取下來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM