搭建Git服务器、编写自动部署脚本

搭建Git服务器、编写自动部署脚本

v2-aad2e9743c39a1299965ed81de0cda26_1200x500.jpg

今天试了下在linux服务器上搭建Git服务器,而且编写一个简单的自动部署脚本。html

主要参考 廖雪峰-GIT教程-搭建Git服务器linux

如今开始吧!git

建立一个git用户,用来运行git服务web

adduser git

建立证书登陆shell

收集全部须要登陆的用户的公钥,就是他们本身的id_rsa.pub文件,把全部公钥导入到/home/git/.ssh/authorized_keys文件里,一行一个。bash

初始化Git仓库服务器

先选定一个目录做为Git仓库,假定是/home/git/sample.git,在/home/git目录下输入命令:ssh

git init --bare sample.git

Git就会建立一个裸仓库,裸仓库没有工做区,由于服务器上的Git仓库纯粹是为了共享,因此不让用户直接登陆到服务器上去改工做区,而且服务器上的Git仓库一般都以.git结尾。而后,把owner改成gitpost

chown -R git:git sample.git

禁用git用户shell登陆spa

经过编辑/etc/passwd文件完成,找到你的git用户的一行,例如:

git:x:1001:1001:,,,:/home/git:/bin/bash

/bin/bash改成/usr/bin/git-shell,例如:

git:x:1001:1001:,,,:/home/git:/usr/bin/git-shell

这样,git用户能够正常经过ssh使用git,但没法登陆shell,由于咱们为git用户指定的git-shell每次一登陆就自动退出。

克隆远程仓库

git clone git@server:sample.git

server是你的服务器域名或ip地址

若是git仓库和web目录在同一台服务器主机上:

git clone /home/git/sample.git

若是不是在git用户的家目录中建立的,好比/srv/gits/sample.git:

git clone git@server:/srv/gits/sample.git

若是clone成功,那么你的git服务器就搭建成功了。

接下来:

自动同步钩子脚本

由于我是web目录和git是同一台服务器

编辑 /home/git/sample.git/hooks/post-receive, post-receive就是在git服务器收到代码推送后(push完成以后)执行的脚本。

#!/bin/sh

while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ "master" == "$branch" ]; then
        # Do something
        echo "post-receive in branch master" >> /tmp/git-sample.log
        unset GIT_DIR
        wwwPath=/var/www/html/sample
        cd $wwwPath && /usr/bin/git pull origin master
        exit 0
    fi
done

从脚本内容能够看出,咱们在判断当前push的分支是master时执行git pull origin master操做。

给执行权限:

chown -R git:git /home/git/sample.git/hooks/post-receive
chmod +x /home/git/sample.git/hooks/post-receive

由于是git仓库和web目录在同一台服务器主机上,这里clone使用的是:

git clone /home/git/sample.git

由于同步脚本的执行用户是git,因此要保证项目目录要赋予git写权限。容易出问题的也是权限问题。

好了,试试吧~

原文链接:

搭建Git服务器-编写自动部署脚本

更多分享知识点,请扫码关注:

v2-7c4116af1e6bc01519bf6eec37a7e855_hd.jpg

相关文章
相关标签/搜索