背景
6 月 6 日,上海交大的 Docker Hub 镜像加速器宣布因收到通知要求被下架。声明称:“即时起我们将中止对 dockerhub 仓库的镜像。docker 相关工具默认会自动处理失效镜像的回退,如果对官方源有访问困难问题,建议尝试使用其他仍在服务的镜像源。我们对给您带来的不便表示歉意,感谢您的理解与支持。”Docker Hub 是目前最大的容器镜像社区,去年 5 月起国内用户报告 Docker Hub 官网无法访问,其网址解析返回了错误 IP 地址。
因为不能直接访问国外的镜像仓库,下载国外的docker镜像速度一直很慢, 国内从 Docker Hub 拉取镜像有时会遇到困难,此时可以配置镜像加速器。
使用
我这边已经部署好了加速镜像节点,同学们如果不想自己部署,可以使用我的加速节点,但是,不能保证节点长期有效。
1https://dockerhub.jobcher.com
第一步:代理拉取镜像
假如我们下载node镜像,那么我们可以这样写:
1docker pull dockerhub.jobcher.com/library/node:latest
2# 或者
3docker pull dockerhub.jobcher.com/bitnami/node:latest
第二步:重命名镜像
1docker tag dockerhub.jobcher.com/library/node:latest node:latest
2# 或者
3docker tag dockerhub.jobcher.com/bitnami/node:latest node:latest
第三步:删除代理镜像
1docker rmi dockerhub.jobcher.com/library/node:latest
2# 或者
3docker rmi dockerhub.jobcher.com/bitnami/node:latest
或者直接配置到镜像仓库
1sudo mkdir -p /etc/docker
2sudo tee /etc/docker/daemon.json <<-'EOF'
3{
4 "registry-mirrors": [
5 "https://dockerhub.jobcher.com",
6 ]
7}
8EOF
重新加载docker
1sudo systemctl daemon-reload
2sudo systemctl restart docker
配置 cloudflare 代理
我们通过 cloudflare 的全球 CDN 节点,以 Workers 中转代理的方式来访问国外镜像仓库,从而加速镜像的下载。
在 Cloudflare Workers 部署一个 Worker 时,它会在30秒之内部署到 Cloudflare 的整个边缘网络,全世界95个国家/200个城市节点。域中的每个请求都会由离用户更近地点的 Worker 来处理,基于此来实现代码的 “随处运行”。
1.创建 Worker
进入Cloudflare Workers
,点击 Create Worker
2.部署 Worker
填写你的环境参数
const hub_host = ‘registry-1.docker.io’
const auth_url = ‘https://auth.docker.io’
填写你的worker page url地址
const workers_url = ‘https://dockerhub.jobcher.com’
粘贴一下到cloudeflare的worker.js中
1'use strict'
2
3const hub_host = 'registry-1.docker.io'
4const auth_url = 'https://auth.docker.io'
5const workers_url = 'https://dockerhub.jobcher.com' //填写你自己的域名地址,不要填写默认的
6/**
7 * static files (404.html, sw.js, conf.js)
8 */
9
10/** @type {RequestInit} */
11const PREFLIGHT_INIT = {
12 status: 204,
13 headers: new Headers({
14 'access-control-allow-origin': '*',
15 'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS',
16 'access-control-max-age': '1728000',
17 }),
18}
19
20/**
21 * @param {any} body
22 * @param {number} status
23 * @param {Object<string, string>} headers
24 */
25function makeRes(body, status = 200, headers = {}) {
26 headers['access-control-allow-origin'] = '*'
27 return new Response(body, {status, headers})
28}
29
30
31/**
32 * @param {string} urlStr
33 */
34function newUrl(urlStr) {
35 try {
36 return new URL(urlStr)
37 } catch (err) {
38 return null
39 }
40}
41
42
43addEventListener('fetch', e => {
44 const ret = fetchHandler(e)
45 .catch(err => makeRes('cfworker error:\n' + err.stack, 502))
46 e.respondWith(ret)
47})
48
49
50/**
51 * @param {FetchEvent} e
52 */
53async function fetchHandler(e) {
54 const getReqHeader = (key) => e.request.headers.get(key);
55
56 let url = new URL(e.request.url);
57
58 if (url.pathname === '/token') {
59 let token_parameter = {
60 headers: {
61 'Host': 'auth.docker.io',
62 'User-Agent': getReqHeader("User-Agent"),
63 'Accept': getReqHeader("Accept"),
64 'Accept-Language': getReqHeader("Accept-Language"),
65 'Accept-Encoding': getReqHeader("Accept-Encoding"),
66 'Connection': 'keep-alive',
67 'Cache-Control': 'max-age=0'
68 }
69 };
70 let token_url = auth_url + url.pathname + url.search
71 return fetch(new Request(token_url, e.request), token_parameter)
72 }
73
74 url.hostname = hub_host;
75
76 let parameter = {
77 headers: {
78 'Host': hub_host,
79 'User-Agent': getReqHeader("User-Agent"),
80 'Accept': getReqHeader("Accept"),
81 'Accept-Language': getReqHeader("Accept-Language"),
82 'Accept-Encoding': getReqHeader("Accept-Encoding"),
83 'Connection': 'keep-alive',
84 'Cache-Control': 'max-age=0'
85 },
86 cacheTtl: 3600
87 };
88
89 if (e.request.headers.has("Authorization")) {
90 parameter.headers.Authorization = getReqHeader("Authorization");
91 }
92
93 let original_response = await fetch(new Request(url, e.request), parameter)
94 let original_response_clone = original_response.clone();
95 let original_text = original_response_clone.body;
96 let response_headers = original_response.headers;
97 let new_response_headers = new Headers(response_headers);
98 let status = original_response.status;
99
100 if (new_response_headers.get("Www-Authenticate")) {
101 let auth = new_response_headers.get("Www-Authenticate");
102 let re = new RegExp(auth_url, 'g');
103 new_response_headers.set("Www-Authenticate", response_headers.get("Www-Authenticate").replace(re, workers_url));
104 }
105
106 if (new_response_headers.get("Location")) {
107 return httpHandler(e.request, new_response_headers.get("Location"))
108 }
109
110 let response = new Response(original_text, {
111 status,
112 headers: new_response_headers
113 })
114 return response;
115
116}
117
118
119/**
120 * @param {Request} req
121 * @param {string} pathname
122 */
123function httpHandler(req, pathname) {
124 const reqHdrRaw = req.headers
125
126 // preflight
127 if (req.method === 'OPTIONS' &&
128 reqHdrRaw.has('access-control-request-headers')
129 ) {
130 return new Response(null, PREFLIGHT_INIT)
131 }
132
133 let rawLen = ''
134
135 const reqHdrNew = new Headers(reqHdrRaw)
136
137 const refer = reqHdrNew.get('referer')
138
139 let urlStr = pathname
140
141 const urlObj = newUrl(urlStr)
142
143 /** @type {RequestInit} */
144 const reqInit = {
145 method: req.method,
146 headers: reqHdrNew,
147 redirect: 'follow',
148 body: req.body
149 }
150 return proxy(urlObj, reqInit, rawLen, 0)
151}
152
153
154/**
155 *
156 * @param {URL} urlObj
157 * @param {RequestInit} reqInit
158 */
159async function proxy(urlObj, reqInit, rawLen) {
160 const res = await fetch(urlObj.href, reqInit)
161 const resHdrOld = res.headers
162 const resHdrNew = new Headers(resHdrOld)
163
164 // verify
165 if (rawLen) {
166 const newLen = resHdrOld.get('content-length') || ''
167 const badLen = (rawLen !== newLen)
168
169 if (badLen) {
170 return makeRes(res.body, 400, {
171 '--error': `bad len: ${newLen}, except: ${rawLen}`,
172 'access-control-expose-headers': '--error',
173 })
174 }
175 }
176 const status = res.status
177 resHdrNew.set('access-control-expose-headers', '*')
178 resHdrNew.set('access-control-allow-origin', '*')
179 resHdrNew.set('Cache-Control', 'max-age=1500')
180
181 resHdrNew.delete('content-security-policy')
182 resHdrNew.delete('content-security-policy-report-only')
183 resHdrNew.delete('clear-site-data')
184
185 return new Response(res.body, {
186 status,
187 headers: resHdrNew
188 })
189}
3. 确认修改
确认修改后,点击 Deploy
按钮,等待部署完成。之后就可以正常使用你的Docker Hub 加速了。