使用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工具把项目拉取下来。

posted @ 2018-11-20 16:04  llxpbbs  阅读(1465)  评论(0编辑  收藏  举报