git服务器实现自动部署

原理与流程

  1. git用户执行git push操作
  2. 远程仓库发现有用户执行了push操作,就会执行一个脚本post-receive(钩子)
  3. post-receive脚本中,将git仓库的代码拷贝到站点目录下

创建git仓库

我们可以在自己的服务器上创建git仓库,有两种方式:

  1. git --bare init (裸仓库)
  2. git init

两者区别:

  1. 普通git仓库的目录结构就和你的代码目录结构一致,只多了.git目录,.git目录中包含了git的一些配置等数据
  2. 裸仓库只保存了一些配置信息等,肉眼是找不到我们所上传的代码的

安装过程  

    (xxxx)指的是仓库的昵称
  1. 在服务器上创建一个裸仓库(git服务器上的远端仓库)

    首先要在服务器上建立一个裸仓库,我存放裸仓库的文件夹是/home/workspace/gitbook,进入到该文件夹,然后使用git init --bare xxxxx.git创建裸仓库。 
    在服务器上创建一个普通Git仓库

  2. 在服务器上建立一个普通Git仓库用于存放网站的源代码。(服务器上的另一个本地仓库)

    mkdir /var/www/workspace
    cd /var/www/workspace
    git clone /home/workspace/gitbook/xxxxx.git    
  3. 配置Git Hook

    进入到/home/workspace/gitbook/xxxx.git/hooks文件夹,使用vi post-receive创建一个脚本,当你在本地仓库执行git push后就会触发post-receive。 

  4. post-receive的内容如下:
     1 #!/bin/sh
     2 
     3 
     4 #判断是不是远端仓库
     5 
     6 IS_BARE=$(git rev-parse --is-bare-repository)
     7 if [ -z "$IS_BARE" ]; then
     8 echo >&2 "fatal: post-receive: IS_NOT_BARE"
     9 exit 1
    10 fi
    11 
    12 unset GIT_DIR
    13 DeployPath="/var/www/workspace/xxxx" //自动部署位置
    14 
    15 echo "==============================================="
    16 cd $DeployPath
    17 echo "deploying the test web"
    18 
    19 #git stash
    20 
    21 #git pull origin master
    22 
    23 git fetch --all
    24 git reset --hard origin/master
    25 
    26 gitbook build
    27 sleep 15
    28 
    29 time=`date`
    30 echo "web server pull at webserver at time: $time."
    31 echo "================================================"
    View Code

    保存后赋予可执行权限:  (复制的时候注意 字符是不是中文 和 是不是少了)

    chmod +x /home/workspace/gitbook/xxxx/hooks/post-receive
  5. 这样在开发者提交代码的时候,就会自动部署。 

在本地提交 可以是ip或域名 214.215.238.xxx 或者 www.xxxx.com      完整地址 是 www.xxxx.com:/home/workspace/gitbook/xxxxx.git  或者 ip:/home/workspace/gitbook/xxxxx.git

借鉴于:http://blog.csdn.net/wsyw126/article/details/52167147 

原文地址:https://www.cnblogs.com/wz-ctt/p/7879151.html