本篇文章需要配合另一篇:将Wordpress静态文件通过Git实时同步到腾讯云Pages
一、 准备工作
安装必要工具
yum install -y epel-release
yum clean all && yum makecache
yum install -y git inotify-tools
二、配置git
1、配置 Git 全局信息
git config --global user.name "ev***"
git config --global user.email "1***@qq.com"

2、 配置 SSH 免密认证
(1) 生成 SSH 密钥
ssh-keygen -t ed25519 -C "*****@qq.com" # 全部回车默认
cat ~/.ssh/id_ed25519.pub # 复制公钥
ssh -T git@gitee.com # 成功会返回 "Hello ev***! You've successfully authenticated..."
3、克隆仓库到本地
cd /opt/1panel/apps/wordpress/MyBlog-wordpress/data
# 直接克隆会提示目录已经存在,因为WP已经生成过静态文件了,直接删除目录,重新创建,并授予777权限,不然docker无法写入文件
rm -rf public_static && mkdir public_static
chmod 777 public_static -R
git clone git@gitee.com:ev936/blog.git public_static # 使用 SSH 地址克隆

三、设置实时同步(inotify-tools)
1、创建同步脚本
cat > /root/gitee_sync.sh << 'EOF'
#!/bin/bash
REPO_DIR="/opt/1panel/apps/wordpress/MyBlog-wordpress/data/public_static"
REMOTE="origin"
BRANCH="master"
LOG_FILE="/var/log/gitee_sync.log"
cd $REPO_DIR || exit 1
while inotifywait -r -e modify,create,delete,move $REPO_DIR; do
echo "[$(date)] 检测到文件变更,开始同步..." >> $LOG_FILE
git add . 2>&1 >> $LOG_FILE
git commit -m "Auto sync: $(date +'%Y-%m-%d %H:%M:%S')" 2>&1 >> $LOG_FILE
git pull $REMOTE $BRANCH 2>&1 >> $LOG_FILE
if git push $REMOTE $BRANCH 2>&1 >> $LOG_FILE; then
echo "同步成功于 $(date)" >> $LOG_FILE
else
echo "[ERROR] 同步失败!请检查日志。" >> $LOG_FILE
fi
done
EOF
2、赋予执行权限
chmod +x /root/gitee_sync.sh
3、创建 Systemd 服务
cat > /etc/systemd/system/gitee-sync.service << 'EOF'
[Unit]
Description=Gitee Auto Sync Service
After=network.target
[Service]
Type=simple
User=root
ExecStart=/bin/bash /root/gitee_sync.sh
Restart=always
StandardOutput=file:/var/log/gitee_sync.log
StandardError=file:/var/log/gitee_sync_error.log
[Install]
WantedBy=multi-user.target
EOF
(4) 启动服务
systemctl daemon-reload
systemctl start gitee-sync
systemctl enable gitee-sync
4、验证同步
(1) 手动测试
touch /root/gitee/test.txt # 创建测试文件
tail -f /var/log/gitee_sync.log # 观察日志是否触发同步
(2) 检查 Gitee 仓库
- 访问
https://gitee.com/e***/blog
,确认test.txt
已推送。
5、最终效果
- 本地 目录的任何修改(增/删/改)会 实时 同步到 Gitee 仓库。
- 日志文件
/var/log/gitee_sync.log
记录所有操作
6、备选方案:Crontab 定时同步(非实时)
如果 inotify-tools
不可靠,可用定时任务:
(crontab -l 2>/dev/null; echo "*/5 * * * * cd /root/gitee && git add . && git commit -m 'Auto sync: \$(date)' && git pull origin master && git push origin master") | crontab -
四、常见问题排查
1、SSH 认证失败
- 运行
ssh -T git@gitee.com
测试连接。 - 确保
~/.ssh/id_ed25519.pub
已正确添加到 Gitee。
2、Git 提交无权限
- 检查仓库是否属于你(或你有推送权限)。
3、脚本未触发
- 手动运行
/root/gitee_sync.sh
观察输出。 - 检查
inotifywait
是否监听到事件:
inotifywait -r -e modify,create,delete,move /root/gitee