# 【GitLab】使用ssh clone 專案

以下是在 GitLab 使用 **SSH** 方式 `clone` 專案的完整步驟，假設你的 GitLab 伺服器是公司內部或自架的，也適用：

---

## 1️⃣ 產生並設定 SSH Key

1. **建立 SSH Key**
    
    ```bash
    ssh-keygen 
    
    ```
    
    
    - 出現檔案路徑提示時直接按 **Enter** (預設<span class="s1">~/.ssh/</span><span class="s1">id\_rsa.pub)</span>
2. - 登入 GitLab → 右上角 **使用者頭像** → **Preferences** → **SSH Keys**。
    - 貼上 <span class="s1">~/.ssh/</span><span class="s1">id\_rsa.pub</span> 內容。

---

## 2️⃣ 測試連線

確認 GitLab 可透過 SSH 連線：

```bash
ssh -T git@your.gitlab.host

```

- 第一次會詢問 `Are you sure you want to continue connecting (yes/no)?` → 輸入 `yes`。
- 成功訊息：`Welcome to GitLab, @你的帳號!`

---

## 3️⃣ 取得專案的 SSH URL

在 GitLab 專案頁面：

- 點選 **Code** → **Clone** → 選 **SSH**。
- 範例 URL：
    
    ```
    git@gitlab.example.com:group-name/project-name.git
    
    ```

---

## 4️⃣ 執行 Clone

```bash
git clone git@gitlab.example.com:group-name/project-name.git

```

- 會將程式碼拉到目前目錄下的 `project-name` 資料夾。

---

## 5️⃣ 常見問題排查

<table id="bkmrk-%E5%95%8F%E9%A1%8C-%E6%AA%A2%E6%9F%A5%E6%96%B9%E5%BC%8F-permission-d"><thead><tr><th>問題</th><th>檢查方式</th></tr></thead><tbody><tr><td>**Permission denied (publickey)**</td><td>確認 `ssh-agent` 有加入金鑰：`ssh-add -l`</td></tr><tr><td>**找不到 Host**</td><td>檢查網路、防火牆，或在 `~/.ssh/config` 加入 Host 設定</td></tr><tr><td>**公司內網 GitLab**</td><td>需確保內部 DNS 或 VPN 正確</td></tr></tbody></table>

---

### 範例 `.ssh/config`（可簡化命令）

```text
Host gitlab-company
    HostName gitlab.example.com
    User git
    IdentityFile ~/.ssh/id_ed25519

```

然後可用：

```bash
git clone git@gitlab-company:group-name/project-name.git

```

---

以上步驟完成後，你就能用 SSH 方式安全地 `git clone` GitLab 專案並進行後續開發。