用git做web应用自动部署
2017-03-04
准备要把shabao.io弄起来
用git往web server上push来迭代挺方便的
参考了网上的文章还是踩了些坑 这里简要记一下步骤(服务器用的ubuntu)
本文只是简单的应用步骤介绍 前置知识请自行古哥 “ssh密钥” “git仓库” “git hooks”等
花点时间写了相关脚本放到gayhub上:
https://github.com/noodlefighter/sh/tree/master/gitserver
1.git用户配置
直接写了个bash脚本..
ssh权限设置要求比较严格..折腾了好久
把ssh-ras公钥放authorized_keys里
git_adduser.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #!/bin/sh
adduser git
mkdir /home/git/.ssh echo "" > /home/git/.ssh/authorized_keys
chown git:git /home/git chmod 755 /home/git
chown git:git /home/git/.ssh chmod 700 /home/git/.ssh
chown git:git /home/git/.ssh/authorized_keys chmod 400 /home/git/.ssh/authorized_keys
sed -i '/^git:*/s;/bin/bash;/usr/bin/git-shell;' /etc/passwd
|
2.建git仓库
这里也直接写了个脚本:
- 建git仓库
- 建发布目录, 设置适当权限: 目录开启执行权限, .git目录禁止其他用户访问(防止源码暴露)
- 复制hooks脚本到仓库的hooks文件夹, 改写发布目录, 开启执行权限
顺便hooks是git的一种类似回调的机制 特定事件发生时执行对应脚本 资料很多 这里就不细说
git_autodeploy.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #!/bin/sh
if [ "$1" = "" ]; then echo "folder error" exit fi if [ "$2" = "" ]; then echo "deploy folder error" exit fi
DIR="$( cd "$( dirname "$0" )" && pwd )"
sudo git init --bare $1
rm -R $2 git clone $1 $2 chown -R git:git $2 chmod -R 755 $2 chmod -R 700 $2/.git
cp $DIR/_hook_post-receive.txt $1/hooks/post-receive sed -i "s;DeployPath=\"/var/web\";DeployPath='$2';" $1/hooks/post-receive chmod 755 $1/hooks/post-receive sudo chown -R git:git $1
|
_hook_post-receive.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #!/bin/sh
IS_BARE=$(git rev-parse --is-bare-repository) if [ -z "$IS_BARE" ]; then echo >&2 "fatal: post-receive: IS_NOT_BARE" exit 1 fi unset GIT_DIR DeployPath="/var/web" echo "===============================================" cd $DeployPath echo "deploying the test web" #git stash
git fetch --all git reset --hard origin/master git pull time=`date` echo "web server pull at webserver at time: $time." echo "================================================"
|
3.测试
此时在客户端上git push
若成功部署则 回显上文hooks脚本中的提示信息