搭建项目
Git 私有仓库搭建与自动部署配置文档
初始化仓库 - 该命令可以自动生成文件夹
git init --bare /data/git/ec_stock.git
修改目录所属用户及所属组
chown -R wwwgit:wwwgit /data/git/ec_stock.git
克隆地址
wwwgit@[服务器内网IP]:/data/git/ec_stock.git
创建密钥
$ ssh-keygen -t rsa -C "xxx@aliyun.com" -f ~/.ssh/rauck
#在windows 使用 “Git Bash”命令行窗口生成秘钥时,默认是以新的格式生成,所以需要用以下命令生成秘钥
$ ssh-keygen -m PEM -t rsa -b 4096 -C "xxx@aliyun.com" -f ~/.ssh/rauck
说明:-f 把生成好 rsa 公钥私钥文件存放在当前登录用户的 .ssh/rauck 目录中
把生成好的公钥追加到wwwgit 用户的authorized_keys 文件中
$ cat ~/.ssh/rauck.pub >> /home/wwwgit/.ssh/authorized_keys
在当前电脑(windows)中使用密钥克隆、拉取、同步数据
Git clone wwwgit@[服务器公网IP]:/data/git/ec_stock.git
Git pull origin master
Git push origin master
编辑钩子
代码同步到仓库后,需要自动更新到产品环境中,操作如下:
$ cd /data/git/ec_stock.git/hooks
$ vi post-receive
post-receive 脚本内容:
#!/bin/bash
sorted=($(for k in `git branch|perl -pe s/^..//`;do aa=`git log -1 --pretty=format:'%Cgreen %ci' "$k"`;bb=$k;cc="$aa"" $bb";echo $cc;done|sort -r));x=${sorted[4]}; for i in "${!sorted[@]}";do printf "%s\t%s\n" "$i" "${sorted[$i]}"done
# 本服务器PHP环境代码更新操作
if [ $x = 'prod' ]; then
workpath="/data/www/ec_stock/"
git --work-tree=$workpath checkout -f prod
fi
# 另一个服务器的PHP环境代码更新操作
if [ $x = 'prod' ]; then
sh ${GIT_DIR}/hooks/shell_helps/remote_pull.sh
fi
$ vi shell_helps/remote_pull.sh
remote_pull.sh 脚本内容:
#!/bin/bash
remote_user='wwwgit'
remote_passwd='******'
remote_ip='[远端服务器IP]'
date_time=`date -d "1 hour ago" +"%Y-%m-%d %H:%M:%S"`
/usr/bin/expect <<-EOF
set time 30
spawn ssh ${remote_user}@${remote_ip}
expect {
"password:" {send "${remote_passwd}\r"}
"yes/no" {send "yes\r";exp_continue}
}
expect "${remote_user}" {send "cd /data/www/ec_stock/\r"}
expect "${remote_user}" {send "git fetch --all\r"}
expect "${remote_user}" {send "git reset --hard origin/prod\r"}
expect "${remote_user}" {send "git fetch\r"}
expect "${remote_user}" {send "cd /docker/www/ec_stock/\r"}
expect "${remote_user}" {send "git fetch --all\r"}
expect "${remote_user}" {send "git reset --hard origin/prod\r"}
expect "${remote_user}" {send "git fetch\r"}
send "exit\r"
expect eof
EOF
注意:远端需要新增用户、配置私钥、安装expect 工具,在此就不一一说明,看上面的shell 文件也知道操作的。
$ chmod -R 755 post-receive shell_helps/
$ chown -R wwwgit:wwwgit post-receive shell_helps/