Use nginx tcp proxy for github clone

Brief introduction:

  1. Add stream block(layer 4 load balancing) to nginx on proxy server
  2. Allow nginx to bind on specific port
  3. Config and clone at client using the proxy server

Prerequisites

  • Latest NGINX Plus (no extra build steps required) or latest NGINX Open Source built with the <span class="pre">--with-stream</span> configuration flag

Server side

Add stream block to nginx.conf (before http block)

...

stream {
    include /etc/nginx/conf.d/*.stream;
}

http {
......
}

Create conf.d/xxx.stream file

upstream github {
    hash   $remote_addr consistent;
    server github.com:22;
}

server {
    listen  222;
    proxy_connect_timeout   30s;
    proxy_timeout   300s;
    proxy_pass  github;
}

Allow nginx bind to specific ports

If you failed to start nginx due to failed bind port, use semanage to allow

> journalctl -xe
nginx: [emerg] bind() to 0.0.0.0:22022 failed (13: Permission denied)

> semanage port -l | grep http_port_t
http_port_t                    tcp      80, 81, 443, 488, 8008, 8009, 8443, 9000
> semanage port -a -t http_port_t -p tcp 222

Add log for incoming connections

stream {
    # access log
    log_format proxy '$remote_addr [$time_local] '
                     '$protocol $status $bytes_sent $bytes_received '
                     '$session_time "$upstream_addr" '
                     '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
    access_log /var/log/nginx/access-tcp.log proxy;
    open_log_file_cache off;
    
    include /etc/nginx/conf.d/*.stream;
}

Client side

Create ~/.ssh/config

Host github.com
    RSAAuthentication yes
    IdentityFile ~/.ssh/id_rsa
    User [yourusername]

Host [github.yourdomain.com]
    RSAAuthentication yes
    IdentityFile ~/.ssh/id_rsa
    User [yourusername]

Don't forget to make sure file permission

chmod 600 config
chmod 600 id_rsa

Clone your repository using the standard syntax

git clone ssh://git@[github.yourdomain.com]:222/path_to/your_repo.git

By default Gitlab and Github will show the scp like syntax url, and we can not give the custom ssh port.

SCP syntax
[user@]host.xz:path/to/repo.git/

Standard syntax
ssh://[user@]host.xz[:port]/path/to/repo.git/
最后修改:2021-05-26
如果觉得我的文章对你有用,请随意赞赏