安装git
sudo apt-get install git
添加用户
sudo adduser git # 创建一个叫 git 的用户
passwd git # 设置密码(可选)
管理公钥
cat ~/.ssh/id_rsa.pub | pbcopy
将所有用户的公钥放在 /home/git/.ssh/
目录下。将所有的pub内容导入到 /home/git/.ssh/authorized_keys
文件里。
禁用git用户shell登录
修改 /etc/passwd
文件:
将git:x:1000:1000:,,,:/home/git:/bin/bash
改为git:x:1000:1000:,,,:/home/git:/usr/bin/git-shell
初始化Git仓库
cd /home/git/
sudo git init --bare test.git # 创建一个叫 test 的git仓库
sudo chown -R git:git test.git # 修改文件权限
克隆远程仓库
现在可以在客户端运行git clone命令克隆远程仓库了。
git clone [email protected]<SERVER_IP>:/home/git/test.git # 下载 test 仓库
钩子
在服务端的 Git 仓库创建 hooks/post-receive
文件,设置权限 chmod +x post-receive
利用 node-foreman
进行部署
#!/bin/sh
export GIT_WORK_TREE="/home/quiz/app"
cd "$GIT_WORK_TREE" || exit
unset GIT_DIR
echo "--> Running deploy script..."
nohup sh $GIT_WORK_TREE/deploy.sh > $GIT_WORK_TREE/out.log 2>&1 %
tail $GIT_WORK_TREE/out.log -f
创建 deploy.sh
#!/bin/sh
SERVICE="node server/app.js"
if ps ax | grep -v grep | grep "$SERVICE" > /dev/null
then
SREVICE_ID=`ps aux | grep "$SERVICE" | grep -v grep | awk '{print $2}'`
echo "$SERVICE service already running, with process id $SREVICE_ID..Trying to kill it..."
kill $SREVICE_ID
else
echo "$SERVICE is not running"
fi
echo "--> Pulling latest..."
git pull origin master
echo "--> Restarting app..."
nf stop
nf start web=2
确保 git 有访问这个 deploy.sh
的权限,保证 kill 命令能被执行。
usermod -a -G group git # add a existing user to existing group
chgrp group /home/quiz/app/deploy.sh
负载均衡
安装 nginx
apt-get install nginx
修改 nginx 配置文件
vi etc/nginx/sites-available/default
内容:
upstream node_server_pool {
server <IP>:5000 max_fails=1;
server <IP>:5001 max_fails=1;
}
server {
listen 80;
server_name 120.24.240.228;
location /
{
proxy_pass http://node_server_pool;
proxy_set_header Host <IP>:80;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
- 重启 nginx
/etc/init.d/nginx restart
解决 Host key verification failed 的问题
因为是由服务器的 git 用户触发 git hook,所以脚本中调用的 git pull origin master
会报错,这时只要把 git 的 id_rsa.pub 内容复制到 quiz 的 authorized_keys,再用 git ssh 登录 quiz 一次,就可以了。