目标:让 Linux 服务器通过 SSH 访问公司 GitLab 仓库(免密码 clone / push)。
核心流程只有 4 步:
1️⃣ 生成 SSH key2️⃣ 把公钥添加到 GitLab
3️⃣ 测试 SSH 连接4️⃣ 使用 SSH clone
⭐ 一、在 Linux 服务器生成 SSH 密钥
推荐 ed25519(更安全、更快)
ssh-keygen -t ed25519 -C "your_email"
一路回车即可。
生成后默认文件:
~/.ssh/id_ed25519
~/.ssh/id_ed25519.pub
⭐ 二、查看公钥内容
cat ~/.ssh/id_ed25519.pub
复制整行输出。
⭐ 三、把公钥添加到 GitLab
进入 GitLab:
头像 → Preferences → SSH Keys
或直接:
https://gitlab.xxx.com/-/profile/keys
粘贴公钥 → Add key。
⭐ 四、测试 SSH 连接
ssh -T git@gitlab.xxx.com
第一次会提示:
Are you sure you want to continue connecting?
输入:
yes
成功会看到:
Welcome to GitLab
⭐ 五、使用 SSH clone 项目
在项目页面:
Clone → SSH
得到地址:
git clone git@gitlab.xxx.com:group/project.git
⭐ 六、如果连接失败(最常见问题)
❌ 1. key 未被使用
查看 agent:
ssh-add -l
没有 key:
ssh-add ~/.ssh/id_ed25519
❌ 2. SSH 权限错误
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
❌ 3. GitLab 端口不是 22(企业常见)
测试:
ssh -T -p 2222 git@gitlab.xxx.com
如果是这样,需要 config。
⭐ 七、企业多账号 / 多 key 场景(强烈建议)
编辑:
vim ~/.ssh/config
示例:
Host gitlab-work
HostName gitlab.xxx.com
User git
IdentityFile ~/.ssh/id_ed25519
Port 22
之后 clone:
git clone git@gitlab-work:group/project.git
⭐ 八、服务器访问 GitLab 的网络问题(企业坑点)
如果 ssh 失败:
ssh -v git@gitlab.xxx.com
排查:
✔ VPN✔ 防火墙✔ 公司内网 DNS✔ GitLab 在内网✔ bastion / jump server
⭐ 九、服务器端必须注意的安全点
服务器 key 属于 机器身份
建议:
✔ 不要使用个人 key✔ 给服务器创建独立 GitLab 账号✔ 或使用 deploy key(更规范)
⭐ 十、Deploy Key(更专业做法)
在项目:
Project → Settings → Repository → Deploy Keys
优点:
✔ 只读 / 可控✔ 不绑定用户✔ 更安全✔ 适合服务器