DEV Community

giveitatry
giveitatry

Posted on

How to Add an SSH Key to GitLab

Using SSH keys to access GitLab allows you to securely connect to your repositories without needing to enter your username and password every time. Here’s a quick guide to generate and add an SSH key to your GitLab account.

Step 1: Generate an SSH Key (if you don’t have one)

Open your terminal and run the following command:

ssh-keygen -t ed25519 -C "your_email@example.com"
Enter fullscreen mode Exit fullscreen mode

If you're on an older system that doesn't support Ed25519, use:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter fullscreen mode Exit fullscreen mode
  • When prompted for a file to save the key, press Enter to accept the default location (~/.ssh/id_ed25519).
  • You can set a passphrase for added security or press Enter to leave it empty.

Step 2: Copy Your Public Key

Display your newly created public key:

cat ~/.ssh/id_ed25519.pub
Enter fullscreen mode Exit fullscreen mode

Copy the entire output — it starts with ssh-ed25519 (or ssh-rsa) and ends with your email.

Step 3: Add the Key to GitLab

  1. Go to GitLab and log in.
  2. In the top-right corner, click your profile icon and select Preferences.
  3. Navigate to SSH Keys from the left sidebar.
  4. Paste your copied key into the Key field.
  5. Optionally, set an expiry date for the key.
  6. Click Add key.

What Is git@gitlab.com?

The address git@gitlab.com is used to securely connect to GitLab’s hosted repositories via SSH.

  • git is the SSH user used for Git operations (not a shell login).
  • gitlab.com is the host of the GitLab server.

When cloning a repository, you might see an SSH URL like:

git@gitlab.com:username/project.git
Enter fullscreen mode Exit fullscreen mode

To test your connection to GitLab via SSH, run:

ssh -T git@gitlab.com
Enter fullscreen mode Exit fullscreen mode

If successful, you will see:

Welcome to GitLab, @yourusername!
Enter fullscreen mode Exit fullscreen mode

Testing SSH Connection to a Local GitLab Server

If you’re using a self-hosted GitLab, replace gitlab.com with your server’s domain or IP address.

Example:

ssh -T git@gitlab.local
# or
ssh -T git@192.168.1.100
Enter fullscreen mode Exit fullscreen mode

If everything is set up correctly, you should see a welcome message.

If access fails:

  • Make sure the SSH port is open on your server.
  • Ensure your SSH public key is added to your GitLab user profile.

Optional: Simplify Access with SSH Config

You can add an alias for your GitLab server in ~/.ssh/config:

Host gitlab-local
    HostName gitlab.local   # or use IP address
    User git
    IdentityFile ~/.ssh/id_ed25519
Enter fullscreen mode Exit fullscreen mode

Now you can connect with:

ssh -T git@gitlab-local
Enter fullscreen mode Exit fullscreen mode

And clone repos like:

git clone git@gitlab-local:groupname/project.git
Enter fullscreen mode Exit fullscreen mode

Top comments (0)