nginx代理nexus实现docker和maven公用端口

/ nginx / 没有评论 / 2014浏览

nginx代理nexus实现docker和maven公用端口

需求

公司使用Nexus作为maven,npm和docker镜像加速服务器;不过Nexus支持docker镜像服务时,需要单独开端口,个人不喜欢这个模式,因此使用Nginx做一层代理,同时开启HTTPS访问。

原理

新版本docker(1.8以后版本)客户端在下载和推送docker镜像时都使用/v2/这个路径,因此可以根据这个条件进行端口转发。

环境

测试发现nexus响应的html和js文件中包含写死的服务端地址,因此还需要使用ngx_http_sub_module来修改响应。可以通过nginx -V | grep http_sub_module来检查是否已经包含的这个模块

代码:内网http版

只使用http的80端口进行访问,编辑/etc/nginx/conf.d/default.conf配置内容:

# 支持推送大文件
client_max_body_size 4096m;

server{
    # 填写真实内网IP,或者用下划线代替所有
    server_name 192.168.50.3;
    listen 80;
    location / {
        proxy_pass http://192.168.50.3:8081;     
        # 关键,替换相应的html和js文件中写死的地址
        sub_filter_types text/html application/x-javascript;
        sub_filter 'http://192.168.50.3:8081' 'http://192.168.50.3';
        sub_filter_once off;
    }

    # 转发所有docker客户端请求到8443端口
    location /v2/ {
        # 在nexus中配置的docker-public仓库端口
        proxy_pass http://192.168.50.3:8443;
    }
}

代码:内网https版本

# 支持推送大文件
client_max_body_size 4096m;

server{
    # 填写真实内网IP,或者用下划线代替所有
    server_name 192.168.50.3;
    listen 80;
    # 跳转https端口
    return 301 https://192.168.50.3$request_uri;
}

server{
    server_name 192.168.50.3;
    # Nginx新版本配置语法
    listen 443 ssl;
    # 这里使用的是自签名的证书,需要替换成你自己的
    ssl_certificate /certs/selfsign/fullchain.cer;
    ssl_certificate_key /certs/selfsign/lan50.key;
    # ssl配置套路
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;


    location / {
        # nexus的默认端口号8081
        proxy_pass http://192.168.50.3:8081;
        # 关键,需要替换相应的html和js文件中写死的地址
        sub_filter_types text/html application/x-javascript;
        sub_filter 'http://192.168.50.3:8081' 'https://192.168.50.3';
        sub_filter_once off;
    }

    # 转发所有docker客户端请求到8443端口
    location /v2/ {
        # 在nexus中配置的docker-public仓库端口
        proxy_pass http://192.168.50.3:8443;
    }
}

代码:公网https版本

和内网https版本基本相同,主要是域名不同

# 支持推送大文件
client_max_body_size 4096m;

server {
    server_name mirror.example.com;
    listen 80;
    # http跳转https的套路配置
    return 301 https://mirror.example.com$request_uri;
}

server{
    server_name mirror.example.com;
    # ssl的套路配置
    listen 443 ssl;
    ssl_certificate /certs/fullchain.cer;
    ssl_certificate_key /certs/server.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;


    location / {
        proxy_pass http://192.168.50.3:8081;
        # 重要,需要替换相应的html和js文件中写死的地址
        sub_filter_types text/html application/x-javascript;
        sub_filter 'http://192.168.50.3:8081' 'https://mirror.kjlink.cloud';
        sub_filter_once off;
    }

    # 转发所有docker客户端请求到8443端口
    location /v2/ {
        proxy_pass http://192.168.50.3:8443;
    }
}