作为运维工程师,我们经常遇到这样的场景:同一个项目需要在多台服务器上部署运行,每次代码更新都要手动逐台服务器上传,既耗时又容易出错。我曾经维护过5台生产服务器,每次发版都要重复5次相同的操作,直到有一天漏传了一台服务器导致线上事故,才痛定思痛寻找自动化解决方案。
GitHub作为最流行的代码托管平台,其实可以成为我们的同步中枢。通过SSH密钥认证和Git命令的组合,我们能实现:
关键提示:国内服务器访问GitHub可能出现连接不稳定,建议先执行
ping github.com测试网络状况。若出现超时,可尝试修改hosts文件或配置代理(需符合企业网络政策)。
在开始前,每台服务器需要满足:
git --version验证)bash复制git config --global user.name "YourName"
git config --global user.email "your@email.com"
相比传统的RSA算法,ED25519具有:
在每台服务器执行:
bash复制ssh-keygen -t ed25519 -C "server-identifier"
bash复制cat ~/.ssh/id_ed25519.pub
避坑指南:复制公钥时务必确认:
- 没有多余空格或换行
- 包含开头的
ssh-ed25519和结尾的注释- 整个密钥为单行文本
执行验证命令:
bash复制ssh -T git@github.com
成功响应应包含:
code复制Hi username! You've successfully authenticated...
常见问题排查:
ssh-keyscan github.com >> ~/.ssh/known_hosts在有代码的服务器(假设为Server-A)操作:
bash复制cd /path/to/project
git init
git add .
git commit -m "Initial commit"
关键参数说明:
git add .:添加所有文件(排除.gitignore定义的)bash复制git remote add origin git@github.com:username/repo.git
git branch -M main # 确保分支名与GitHub默认一致
git push -u origin main
操作细节:
-u参数设置上游分支,后续可直接用git push不带参数
在其他服务器执行:
bash复制cd /target/path
git clone git@github.com:username/repo.git
为避免路径混乱,推荐方案:
code复制/opt/
└── projects/
└── repo-name/ # 克隆的仓库
├── .git/
└── ... # 项目文件
对于生产环境:
bash复制sudo chown -R deploy:deploy /opt/projects/repo-name
sudo chmod -R 750 /opt/projects/repo-name
bash复制git status
git diff
bash复制git add path/to/file
bash复制git commit -m "描述性信息"
bash复制git push
bash复制git pull --rebase
使用rebase避免多余的合并提交
bash复制git stash
git pull --rebase
git stash pop
冲突解决流程:
<<<<<<<标记)bash复制git add conflicted_file
bash复制git rebase --continue
为避免混乱,建议:
bash复制git checkout -b hotfix-server1
# 修改后
git push origin hotfix-server1
然后在主开发机合并PR
通过crontab实现定时同步:
bash复制# 每天凌晨3点自动拉取更新
0 3 * * * cd /opt/projects/repo && git pull --rebase >> /var/log/git-sync.log 2>&1
当项目包含大文件时:
bash复制sudo apt-get install git-lfs
git lfs install
bash复制git lfs track "*.psd"
对于包含子模块的项目:
bash复制git submodule update --init --recursive
| 错误现象 | 可能原因 | 解决方案 |
|---|---|---|
fatal: not a git repository |
未在仓库目录执行 | cd到正确目录 |
Permission denied (publickey) |
SSH密钥未生效 | 检查密钥是否添加到GitHub |
Could not resolve hostname |
DNS解析问题 | 在/etc/hosts添加140.82.121.3 github.com |
Automatic merge failed |
存在冲突 | 手动解决冲突后提交 |
查看详细错误信息:
bash复制GIT_TRACE=1 GIT_SSH_COMMAND="ssh -v" git pull
当.git目录损坏时:
bash复制git fsck
git reflog
git reset --hard HEAD@{1}
bash复制ssh-keygen -p -f ~/.ssh/id_ed25519
bash复制sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
绝对不要提交:
推荐使用:
bash复制git secret
或环境变量管理
bash复制git clone --depth 1 git@github.com:user/repo.git
bash复制git config core.sparseCheckout true
echo "src/" >> .git/info/sparse-checkout
git pull origin main
bash复制git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
通过分支区分配置:
code复制main # 生产环境配置
staging # 预发布环境
development # 开发环境
结合Webhook实现:
定期将GitHub仓库镜像到其他平台:
bash复制git remote set-url --add --push origin git@backup-site.com:user/repo.git