使用短域名提供 Docker 镜像

原理是基于方向代理,例如镜像源为 docker-library.example.com,想要使用 example.com/<仓库名> 或者 example.com/<用户名>/<仓库名> 的方式来访问镜像;同时正常的 HTTP 访问依然返回 HTML 页面。

需要注意的是,此方案会导致 /v2 开头的 URL 被路由到 Docker Registry,因此您设计的 Web 页面不能包含 /v2 开头的 URL。

Nginx 配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
location /v2 {
# 对于 example.com/<仓库名> ,默认路由到 _library 用户名(即 docker-library.example.com/_library/<仓库名>)
if ($uri ~ ^/v2/(?<image>[^/]+)/(?<resource>manifests|blobs)(?<suffix>/.*)?$) {
rewrite ^/v2/(?<image>[^/]+)/(?<resource>manifests|blobs)(?<suffix>/.*)?$ /v2/_library/$image/$resource$suffix last;
}
# 对于 example.com/<用户名>/<仓库名> ,路由到 docker-library.example.com/<用户名>/<仓库名>
if ($uri ~ ^/v2/(?<user>[^/]+)/(?<image>[^/]+)/(?<resource>manifests|blobs)(?<suffix>/.*)?$) {
rewrite ^/v2/(?<user>[^/]+)/(?<image>[^/]+)/(?<resource>manifests|blobs)(?<suffix>/.*)?$ /v2/$user/$image/$resource$suffix last;
}
proxy_pass https://docker-library.example.com;
proxy_set_header Host docker-library.example.com;
proxy_set_header X-Real-IP $remote_addr;
}

proxy_set_header 选项可以根据需要添加。