GitLab – Fix Permission Denied (publickey) Error on Self-Hosted Server

docker-composegitlabssh

I want to setup a ssh connection to my gitlab server.

gitlab spec

Install via docker-compose :

# ---------------------- #
#         gitlab         #
# ---------------------- #
gitlab:
  image: gitlab/gitlab-ce:latest
  restart: always
  hostname: gitlab.host.dev
  ports:
    - '801:80'
    - '4433:443'
    - '2222:22'
  volumes:
    - ./config:/etc/gitlab
    - ./logs:/var/log/gitlab
    - ./data:/var/opt/gitlab
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url 'http://gitlab.host.dev'
      gitlab_rails['smtp_enable'] = true
      gitlab_rails['smtp_address'] = "smtp.gmail.com"
      gitlab_rails['smtp_port'] = 587
      gitlab_rails['smtp_user_name'] = "a@gmail.com"
      gitlab_rails['smtp_password'] = "xyz"
      gitlab_rails['smtp_domain'] = "smtp.gmail.com"
      gitlab_rails['smtp_authentication'] = "login"
      gitlab_rails['smtp_enable_starttls_auto'] = true
      gitlab_rails['smtp_tls'] = false
      gitlab_rails['smtp_openssl_verify_mode'] = 'peer'

In the image :

cd /opt/gitlab/embedded/service/gitlab-shell/

ls -al

[...]
lrwxrwxrwx  1 root root    39 Sep  7 18:19 config.yml -> /var/opt/gitlab/gitlab-shell/config.yml
[...]

cd /var/opt/gitlab/.ssh/

ls -al

-rw-------  1 git  git  3036 Sep 10 08:30 authorized_keys
-rw-r--r--  1 git  git     0 Sep 10 08:30 authorized_keys.lock

Step

  1. I add the key on the SSH Keys setting (for my user in gitlab)
ssh-rsa AAAAAAAAAAA= user@hostname
  1. I create a project test_ssh in my gitlab
  2. I create a new folder in my computer mkdir test_ssh and touch test.txt
  3. git init
  4. git add .
  5. git commit -am "initial commit
  6. add the gitlab remote git remote add origin git@gitlab.dn.dev:gitlabuser/test_ssh.git
  7. git push -u origin master

Error

git@gitlab.helyx.dev: Permission denied (publickey).
fatal: Can not read remote depot.

Please check that you have access rights
and that the deposit exists.

Https test

I test the push via https and is work correctly.

  1. git remote add https https://gitlab.dn.dev/user/test_ssh.git
  2. git push -u https master
To https://gitlab.dn.dev/user/test_ssh.git
   * [new branch]      master -> master

Best Answer

You have configured your container to expose ssh on port 2222:

  ports:
    - '2222:22'

But you are not providing the port in your git remote URL. You need to add the port 2222 to your remote URL, something like this:

git remote add origin ssh://git@gitlab.dn.dev:2222/test_ssh.git

Without this port you are connecting to the SSHd of the server itself, not the one provided by Gitlab.

Other options to provide the port are listed here.