Search code examples
nginxgitlabreverse-proxyssh-tunnel

Git clone through Nginx proxy for Gitlab server is not working


My Nginx Server is acting as a proxy for a Gitlab Server, the problem is when I try "**git clone git@gitlab.example.com:username/project.git**" I'm unable to clone the project [it is not tunneling from Nginx server to Gitlab server]

When I update my local system's /etc/hosts file with IP Address of Gitlab Server then it clones fine without password [I've updated my profile with SSH Public Key on Gitlab].

So I came to the conclusion that I've to update my Nginx Configuration with rules that can tunnel the SSH communication from any client system to Gitlab Server through Nginx Server.

Tried the code on this Link by making changes as followed:

upstream gitlab {
server 192.168.61.102:22;
}

server {
listen 22;
server_name gitlab.example.com;

location / {
proxy_set_header  X-Real-IP  $remote_addr;
proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;

proxy_pass http://gitlab;
}
}

but it is not working. It would be great if someone helps me in tweaking the rules to make it work.

Note: In the above code 192.168.61.102 is the IP Address of my gitlab server, my Nginx server is at 192.168.61.101


Solution

  • First, you need to stop having Nginx listen on port 22. Nginx doesn't handle SSH forwarding, your firewall does.

    If you're using iptables, then these rules will forward all requests through your Nginx host to your Gitlab host.

    sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 22 -j DNAT --to-destination [GITLAB-IP]:22
    sudo iptables -t nat -A POSTROUTING -o eth0 -p tcp --dport 22 -j SNAT --to-source [NGINX-IP]
    

    You may need to change eth0 in those commands to fit your server setup.


    Then you need to enable packet forwarding by editing the /etc/sysctl.conf file and uncommenting this line:

    net.ipv4.ip_forward=1
    

    Then reload the configuration you just changed with this command:

    sudo sysctl -p
    

    Finally, those iptables rule are not persistent by default and will be erased when you reboot the server. The easiest way to make them persistent is to use the iptables-persistent package. You install that package like this:

    sudo apt-get install iptables-persistent
    

    And after it's installed you can save/restore the iptables rules anytime with these commands:

    sudo invoke-rc.d iptables-persistent save
    sudo invoke-rc.d iptables-persistent reload
    

    If you're on Ubuntu 16.04 or later, then those commands are

    sudo netfilter-persistent save
    sudo netfilter-persistent reload
    

    You'll want to run the save command after you get the rules working and you've tested them. Then, when your server reboots the rules you saved will be loaded automatically.