📖 本文面向需要将GitHub开源项目镜像到自建GitLab服务器的开发者,提供全链路同步方案(手动+自动),解决代码库双向维护难题。
📋 场景说明
- 原始仓库:
https://github.com/your-project.git
- 目标仓库:
ssh://git@xxxxxxxxx/your-project.git
- 需求
- 本地保留GitHub原始仓库更新能力
- 自动/手动推送代码到私有GitLab
- 长期保持双端代码一致
🛠️ 环境准备
- Git客户端(>=2.0)
- GitHub账号(只读权限)
- GitLab服务器访问权限(需配置SSH密钥)
🔧 完整实现步骤
一、初始配置:关联双仓库
# 克隆GitHub仓库
git clone https://github.com/your-project.git
cd your-project
# 添加私有GitLab远程(命名为gitlab)
git remote add gitlab ssh://git@xxxxxxxxx/your-project.git
# 添加原始GitHub仓库为上游(命名为upstream)
git remote add upstream https://github.com/your-project.git
# 若提示upstream已存在 git remote rm origin 后重新添加
✅ 验证远程配置
git remote -v
输出应包含:
upstream
-> GitHub地址gitlab
-> 私有GitLab地址
二、首次推送代码到GitLab
# 推送main分支(如使用master分支请自行替换)
git push -u gitlab main
# 推送所有分支和标签(可选)
git push --all gitlab
git push --tags gitlab
三、手动同步更新流程
当GitHub仓库有更新时:
# 1. 拉取上游更新
git fetch upstream
# 2. 合并到本地分支
git checkout main
git merge upstream/main
# 3. 推送到私有GitLab
git push gitlab main
# 可选:强制覆盖(慎用)
git push -f gitlab main
四、自动同步方案(GitHub Actions)
(图:GitHub Actions工作流示意图)
1. 配置仓库Secrets
进入GitHub仓库:
Settings > Secrets > Actions ➕ 新建:
Secret名称 | 值 |
---|---|
GITLAB_USERNAME | git(或你的GitLab用户名) |
GITLAB_TOKEN | GitLab的访问令牌 |
🔑 令牌需勾选
write_repository
权限
2. 创建Action工作流
新建文件 .github/workflows/sync-to-gitlab.yml
:
name: Auto Sync to GitLab
on:
push: # GitHub仓库有提交时触发
branches: [ main ]
schedule: # 每天UTC 0点同步(可选)
- cron: '0 0 * * *'
jobs:
mirror:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Configure Git
run: |
git config --global user.name "GitHub Sync Bot"
git config --global user.email "actions@github.com"
- name: Push to GitLab
run: |
git remote add gitlab http://${{ secrets.GITLAB_USERNAME }}:${{ secrets.GITLAB_TOKEN }}@xxxxxxxxx/your-project.git
git push gitlab main
3. 触发工作流
提交代码后查看运行状态:
GitHub仓库 > Actions > Auto Sync to GitLab
五、SSH密钥配置(如需要)
# 生成Ed25519密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"
# 复制公钥到剪贴板
cat ~/.ssh/id_ed25519.pub | pbcopy
# 添加公钥到GitLab
# 进入 GitLab -> Settings -> SSH Keys 粘贴
⚠️ 注意事项
-
网络连通性
- 确保GitLab服务器的
2222
端口对GitHub Actions Runner开放 - 企业内网建议配置反向代理或VPN
- 确保GitLab服务器的
-
分支保护
- 在GitLab设置
main
分支为受保护分支 - 禁止直接向GitLab推送代码(仅允许镜像同步)
- 在GitLab设置
-
冲突处理
- 建议始终保持GitLab为只读镜像
- 如必须修改,优先在GitHub操作后重置GitLab仓库:
git push --force gitlab main
📊 方案对比
方式 | 实时性 | 复杂度 | 适用场景 |
---|---|---|---|
手动同步 | 低 | 简单 | 低频更新 |
GitHub Actions | 高 | 中等 | 需实时同步 |
镜像仓库功能 | 高 | 简单 | GitLab企业版用户 |
🌟 总结
通过本文的配置,您已实现:
- GitHub代码变更实时/定时同步到私有GitLab
- 本地开发环境与双仓库的无缝对接
- 企业级代码镜像的安全控制
遇到问题?欢迎在评论区留言交流!
📌 相关推荐
- Git多远程仓库管理高阶技巧
- GitHub Actions官方文档:中文版
请根据实际服务器地址和分支名称调整代码片段。建议在正式发布时补充操作截图以提升教程易用性。