本文面向需要将GitHub开源项目镜像到自建GitLab服务器的开发者,提供全链路同步方案(手动+自动),解决代码库双向维护难题。
https://github.com/your-project.git
ssh://git@xxxxxxxxx/your-project.git
# 克隆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地址# 推送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仓库:
Settings > Secrets > Actions ➕ 新建:
Secret名称 | 值 |
---|---|
GITLAB_USERNAME |
git(或你的GitLab用户名) |
GITLAB_TOKEN |
GitLab的访问令牌 |
令牌需勾选
write_repository
权限
新建文件 .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 "[email protected]"
- name: Push to GitLab
run: |
git remote add gitlab http://${{ secrets.GITLAB_USERNAME }}:${{ secrets.GITLAB_TOKEN }}@xxxxxxxxx/your-project.git
git push gitlab main
提交代码后查看运行状态:
GitHub仓库 > Actions > Auto Sync to GitLab
# 生成Ed25519密钥对
ssh-keygen -t ed25519 -C "[email protected]"
# 复制公钥到剪贴板
cat ~/.ssh/id_ed25519.pub | pbcopy
# 添加公钥到GitLab
# 进入 GitLab -> Settings -> SSH Keys 粘贴
网络连通性
2222
端口对GitHub Actions Runner开放分支保护
main
分支为受保护分支冲突处理
git push --force gitlab main
方式 | 实时性 | 复杂度 | 适用场景 |
---|---|---|---|
手动同步 | 低 | 简单 | 低频更新 |
GitHub Actions | 高 | 中等 | 需实时同步 |
镜像仓库功能 | 高 | 简单 | GitLab企业版用户 |
通过本文的配置,您已实现:
遇到问题?欢迎在评论区留言交流!
相关推荐
请根据实际服务器地址和分支名称调整代码片段。建议在正式发布时补充操作截图以提升教程易用性。