Linux快速搭建Git服务

我们将git服务部署到linux服务器上,往往出于以下的目的:

  • 保护自己的代码不被他人获取
  • 在推送(push)更新的时候希望同时更新一份最新的代码

那么可以依照下面的步骤搭建一个简单使用的git服务器


一,安装Git服务

这里以CentOS系统为例,执行命令

yum install git -y

Ubuntu/Debian系统下执行命令

apt-get install git -y

查看版本可以看到成功安装

[root@centos74 pyx]# git --version
git version 1.8.3.1

二,准备git账户

Git服务不同于apache,MySQL一样需要在后台不停运行

它基于ssh协议,任何账号都可以使用,比如用户foo在服务器example.com的家目录(home/foo)下建立了一个仓库bar,那么可以使用下面的命令克隆这个仓库

git clone [email protected]:bar

这里通常使用git作为默认账户,使用下面的命令添加账户,并设置密码

useradd git
passwd git

切换到git账户并回到家目录

su git
cd ~

执行下面的命令生产公私钥,并将公钥的内容复制到文件 authorized_keys 中,目的是让git账户可以访问自己简历的仓库

如果是从其他账号或者外部主机访问该仓库,同样也需要将其他账户的公钥追加到authorized_keys文件中

ssh-keygen -t rsa -C [email protected]
git config --global user.name lich4ung
git config --global user.email [email protected]
touch ~/.ssh/authorized_keys
cat ~/.ssh/id_rsa.pub > ~/.ssh/authorized_keys
chmod 0600 ~/.ssh/authorized_keys

我写了一个一键创建仓库的脚本 mkrepo.sh,接受两个参数: 

  1. 仓库名称,执行后会在家目录(/home/git)创建一个同名文件夹,这就是仓库
  2. 钩子指定的分支名称,当有更新推送到该分支时,会自动更新该分支代码

其内容如下:

#!/usr/bin/env bash

REPOSITORY_NAME=$1
BRANCH_NAME=$2
if [ "" = "${BRANCH_NAME}" ]; then
    BRANCH_NAME="master"
fi
cd ~
mkdir ${REPOSITORY_NAME}
cd ${REPOSITORY_NAME}
git --bare init

cd hooks

echo "#!/usr/bin/env bash
# 项目所在目录
BASEDIR=/srv/webroot/
# 项目名称
NAME=${REPOSITORY_NAME}
# post-receive 分支
BRANCH_NAME=${BRANCH_NAME}
WORKSPACE=\${BASEDIR}/\${NAME}/
GIT_DIR=\${WORKSPACE}/.git
GIT_WORK_TREE=\${WORKSPACE}
if [ ! -d \${WORKSPACE} ]; then
    cd \${BASEDIR}
    git clone [email protected]:\${NAME}
    cd \${NAME}
    git checkout \${BRANCH_NAME}
else
    cd \${WORKSPACE}
fi
git pull origin \${BRANCH_NAME}
" >>  post-receive
chmod a+x post-receive

使用示例:

# demo 是仓库名, 更新分支 master
./mkrepo.sh demo 
# 同上
./mkrepo.sh demo master
# 执行更新 feature 分支
./mkrepo.sh demo feature

查看demo仓库下的钩子文件 ~/demo/hooks/post-receive ,可以看到下面的内容,可以知道钩子的本质就是shell脚本

[git@centos74 ~]$ cat /home/git/demo/hooks/post-receive 
#!/usr/bin/env bash
# 项目所在目录
BASEDIR=/srv/webroot/
# 项目名称
NAME=dede
# post-receive 分支
BRANCH_NAME=master
WORKSPACE=${BASEDIR}/${NAME}/
GIT_DIR=${WORKSPACE}/.git
GIT_WORK_TREE=${WORKSPACE}
if [ ! -d ${WORKSPACE} ]; then
    cd ${BASEDIR}
    git clone [email protected]:${NAME}
    cd ${NAME}
    git checkout ${BRANCH_NAME}
else
    cd ${WORKSPACE}
fi
git pull origin ${BRANCH_NAME}

三,准备部署文件夹

在上面提到的脚本中,我们看到了一个文件夹(/srv/webroot),这就是一个部署文件夹,

当给demo仓库推送feature分支时更新一份代码到, /srv/webroot/demo 就会自动更新一份源代码

但在使用前需保证该目录存在,且git账户具有所有权,使用root账户执行下面的脚本

mkdir -p /srv/webroot
chown -R git.git /srv/webroot





猜你喜欢

转载自blog.csdn.net/acer_antor/article/details/80494645
今日推荐