Git Hook 自动部署指南
通过配置 Git Hook,你可以实现 git push 即自动构建并部署文档到服务器。这种方式简单高效,适合个人或小团队项目。
前置要求
- 服务器: 一台安装了 Linux 的服务器(如 Ubuntu/CentOS)。
- 软件: 服务器需安装 Git, Node.js (建议 v18+), Nginx (或 Apache)。
- 权限: 拥有服务器的 SSH 访问权限。
1. 服务器端配置
登录到你的服务器,执行以下步骤。
1.1 创建裸仓库 (Bare Repository)
裸仓库没有工作目录,只存储 Git 数据,非常适合作为远程仓库。
bash
# 创建存放 git 仓库的目录
mkdir -p /home/git/repos
cd /home/git/repos
# 初始化裸仓库
git init --bare flu-cli-docs.git1.2 创建网站根目录
这是文档构建后文件存放的地方。
bash
# 创建网站根目录
mkdir -p /var/www/flu-cli-docs
# 确保当前用户有写入权限 (假设当前用户是 ubuntu)
chown -R ubuntu:ubuntu /var/www/flu-cli-docs1.3 配置 post-receive Hook
post-receive 钩子会在代码推送到仓库后触发。
bash
# 进入 hooks 目录
cd /home/git/repos/flu-cli-docs.git/hooks
# 创建 post-receive 文件
nano post-receive将以下内容复制到 post-receive 文件中:
bash
#!/bin/bash
# 配置
TARGET="/var/www/flu-cli-docs"
GIT_DIR="/home/git/repos/flu-cli-docs.git"
BRANCH="main"
while read oldrev newrev ref
do
# 只有推送到 main 分支才部署
if [[ $ref =~ .*/$BRANCH$ ]];
then
echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
# 创建临时目录用于构建
TEMP_DIR=$(mktemp -d)
echo "Checking out code to temporary directory..."
git --work-tree=$TEMP_DIR --git-dir=$GIT_DIR checkout -f $BRANCH
echo "Installing dependencies and building..."
cd $TEMP_DIR
# 安装依赖并构建
# 注意:确保 npm 在 PATH 中,或者使用绝对路径
npm install
npm run docs:build
# 将构建产物移动到目标目录
echo "Deploying to $TARGET..."
# 清空目标目录(保留 .git 等隐藏文件如果需要的话,这里直接覆盖)
rm -rf $TARGET/*
cp -r .vitepress/dist/* $TARGET/
# 清理临时目录
cd /
rm -rf $TEMP_DIR
echo "Deployment complete!"
else
echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
fi
done1.4 赋予执行权限
bash
chmod +x post-receive2. 本地配置
在你的本地开发机上进行配置。
2.1 添加远程仓库
将服务器上的裸仓库添加为本地项目的远程仓库。
bash
# 格式: git remote add [名称] [用户]@[服务器IP]:[裸仓库路径]
git remote add deploy ubuntu@1.2.3.4:/home/git/repos/flu-cli-docs.git2.2 推送部署
现在,你可以通过推送到 deploy 远程仓库来触发部署。
bash
git push deploy main如果一切正常,你将在终端看到服务器端的构建输出日志。
3. Nginx 配置 (可选)
如果你还没有配置 Nginx,可以参考以下配置:
nginx
server {
listen 80;
server_name docs.yourdomain.com;
root /var/www/flu-cli-docs;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}常见问题
1. npm: command not found
如果在 hook 执行时提示找不到 npm,请在 post-receive 脚本开头添加 PATH 环境变量,或者使用 npm 的绝对路径(通过 which npm 查看)。
bash
export PATH=$PATH:/usr/local/bin:/usr/bin2. 权限错误
确保执行 hook 的用户对 /var/www/flu-cli-docs 目录有写入权限。