Cirry's Blog

搭建自己的Docker镜像源

2024-11-04
docker docker
14分钟
2627字

背景

不记得多长时间了,反正在群晖上的docker已经很久没办法正常使用了。

每次点到注册表的时候总是提示:无法执行此操作,可能是因为网络连接不稳定或系统正忙,请稍后再试。

这次就来解决一下这个问题吧。

前提

  1. 一个域名

操作流程

1. 登录Cloudflare

注册Cloudflare账号,在网站首页的标题中,可以选择设置为中文,然后点击添加站点

default

域名输入框中输入的是一级域名,类似:baidu.com,cirry.cn这样的一级域名,然后点击继续

2. 选择计划

选择免费计划,点击继续

default

3. 添加DNS记录

如果您是一个新的域名,这个地方应该都是空的,直接点击继续前往激活即可。

如果您是在其他地方已经设置好的域名,那就需要在这个地方补全你之前的dns记录,然后再点击继续前往激活

4. 设置域名的服务商

default

在这一步中,我们需要修改域名的服务上,这里以在腾讯云中购买的域名举例:

在腾讯云控制台中,搜索域名注册,点击刚注册好的域名,点击修改DNS服务器,设置完成后保存记录。

default

5. 确认域名状态

回到cloudflare主页,查看域名状态,当看到域名的状态是活动,说明域名已经生效了,可以继续进行下一步了。

default

6. 添加Workers和Pages

点击左侧的Workers和Pages后,点击右上角的创建按钮。

default

7. 创建worker

直接点击创建worker

default

8. 部署worker

直接点击`部署“。

default

9. 编辑代码

部署完成之后,点击右上角的编辑代码按钮。

default

10. 修改js代码

复制https://raw.githubusercontent.com/cmliu/CF-Workers-docker.io/refs/heads/main/_worker.js 中的代码粘贴到代码框中,点击部署

default

贴上完整代码,这里的代码不一定是最新的,最好是可以去github中复制最新的代码。

worker.js
1
// _worker.js
2
3
// Docker镜像仓库主机地址
4
let hub_host = 'registry-1.docker.io';
5
// Docker认证服务器地址
6
const auth_url = 'https://auth.docker.io';
7
// 自定义的工作服务器地址
8
let workers_url = 'https://xxx/';
9
10
let 屏蔽爬虫UA = ['netcraft'];
11
12
// 根据主机名选择对应的上游地址
13
function routeByHosts(host) {
14
// 定义路由表
15
const routes = {
435 collapsed lines
16
// 生产环境
17
"quay": "quay.io",
18
"gcr": "gcr.io",
19
"k8s-gcr": "k8s.gcr.io",
20
"k8s": "registry.k8s.io",
21
"ghcr": "ghcr.io",
22
"cloudsmith": "docker.cloudsmith.io",
23
"nvcr": "nvcr.io",
24
25
// 测试环境
26
"test": "registry-1.docker.io",
27
};
28
29
if (host in routes) return [ routes[host], false ];
30
else return [ hub_host, true ];
31
}
32
33
/** @type {RequestInit} */
34
const PREFLIGHT_INIT = {
35
// 预检请求配置
36
headers: new Headers({
37
'access-control-allow-origin': '*', // 允许所有来源
38
'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS', // 允许的HTTP方法
39
'access-control-max-age': '1728000', // 预检请求的缓存时间
40
}),
41
}
42
43
/**
44
* 构造响应
45
* @param {any} body 响应体
46
* @param {number} status 响应状态码
47
* @param {Object<string, string>} headers 响应头
48
*/
49
function makeRes(body, status = 200, headers = {}) {
50
headers['access-control-allow-origin'] = '*' // 允许所有来源
51
return new Response(body, { status, headers }) // 返回新构造的响应
52
}
53
54
/**
55
* 构造新的URL对象
56
* @param {string} urlStr URL字符串
57
*/
58
function newUrl(urlStr) {
59
try {
60
return new URL(urlStr) // 尝试构造新的URL对象
61
} catch (err) {
62
return null // 构造失败返回null
63
}
64
}
65
66
function isUUID(uuid) {
67
// 定义一个正则表达式来匹配 UUID 格式
68
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
69
70
// 使用正则表达式测试 UUID 字符串
71
return uuidRegex.test(uuid);
72
}
73
74
async function nginx() {
75
const text = `
76
<!DOCTYPE html>
77
<html>
78
<head>
79
<title>Welcome to nginx!</title>
80
<style>
81
body {
82
width: 35em;
83
margin: 0 auto;
84
font-family: Tahoma, Verdana, Arial, sans-serif;
85
}
86
</style>
87
</head>
88
<body>
89
<h1>Welcome to nginx!</h1>
90
<p>If you see this page, the nginx web server is successfully installed and
91
working. Further configuration is required.</p>
92
93
<p>For online documentation and support please refer to
94
<a href="http://nginx.org/">nginx.org</a>.<br/>
95
Commercial support is available at
96
<a href="http://nginx.com/">nginx.com</a>.</p>
97
98
<p><em>Thank you for using nginx.</em></p>
99
</body>
100
</html>
101
`
102
return text;
103
}
104
105
async function searchInterface() {
106
const text = `
107
<!DOCTYPE html>
108
<html>
109
<head>
110
<title>Docker Hub Search</title>
111
<style>
112
body {
113
font-family: Arial, sans-serif;
114
display: flex;
115
flex-direction: column;
116
align-items: center;
117
justify-content: center;
118
height: 100vh;
119
margin: 0;
120
background: linear-gradient(to right, rgb(28, 143, 237), rgb(29, 99, 237));
121
}
122
.logo {
123
margin-bottom: 20px;
124
}
125
.search-container {
126
display: flex;
127
align-items: center;
128
}
129
#search-input {
130
padding: 10px;
131
font-size: 16px;
132
border: 1px solid #ddd;
133
border-radius: 4px;
134
width: 300px;
135
margin-right: 10px;
136
}
137
#search-button {
138
padding: 10px;
139
background-color: rgba(255, 255, 255, 0.2); /* 设置白色,透明度为10% */
140
border: none;
141
border-radius: 4px;
142
cursor: pointer;
143
width: 44px;
144
height: 44px;
145
display: flex;
146
align-items: center;
147
justify-content: center;
148
}
149
#search-button svg {
150
width: 24px;
151
height: 24px;
152
}
153
</style>
154
</head>
155
<body>
156
<div class="logo">
157
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" fill="#ffffff" width="100" height="75">
158
<path d="M23.763 6.886c-.065-.053-.673-.512-1.954-.512-.32 0-.659.03-1.01.087-.248-1.703-1.651-2.533-1.716-2.57l-.345-.2-.227.328a4.596 4.596 0 0 0-.611 1.433c-.23.972-.09 1.884.403 2.666-.596.331-1.546.418-1.744.42H.752a.753.753 0 0 0-.75.749c-.007 1.456.233 2.864.692 4.07.545 1.43 1.355 2.483 2.409 3.13 1.181.725 3.104 1.14 5.276 1.14 1.016 0 2.03-.092 2.93-.266 1.417-.273 2.705-.742 3.826-1.391a10.497 10.497 0 0 0 2.61-2.14c1.252-1.42 1.998-3.005 2.553-4.408.075.003.148.005.221.005 1.371 0 2.215-.55 2.68-1.01.505-.5.685-.998.704-1.053L24 7.076l-.237-.19Z"></path>
159
<path d="M2.216 8.075h2.119a.186.186 0 0 0 .185-.186V6a.186.186 0 0 0-.185-.186H2.216A.186.186 0 0 0 2.031 6v1.89c0 .103.083.186.185.186Zm2.92 0h2.118a.185.185 0 0 0 .185-.186V6a.185.185 0 0 0-.185-.186H5.136A.185.185 0 0 0 4.95 6v1.89c0 .103.083.186.186.186Zm2.964 0h2.118a.186.186 0 0 0 .185-.186V6a.186.186 0 0 0-.185-.186H8.1A.185.185 0 0 0 7.914 6v1.89c0 .103.083.186.186.186Zm2.928 0h2.119a.185.185 0 0 0 .185-.186V6a.185.185 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm-5.892-2.72h2.118a.185.185 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186H5.136a.186.186 0 0 0-.186.186v1.89c0 .103.083.186.186.186Zm2.964 0h2.118a.186.186 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186H8.1a.186.186 0 0 0-.186.186v1.89c0 .103.083.186.186.186Zm2.928 0h2.119a.185.185 0 0 0 .185-.186V3.28a.186.186 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm0-2.72h2.119a.186.186 0 0 0 .185-.186V.56a.185.185 0 0 0-.185-.186h-2.119a.186.186 0 0 0-.185.186v1.89c0 .103.083.186.185.186Zm2.955 5.44h2.118a.185.185 0 0 0 .186-.186V6a.185.185 0 0 0-.186-.186h-2.118a.185.185 0 0 0-.185.186v1.89c0 .103.083.186.185.186Z"></path>
160
</svg>
161
</div>
162
<div class="search-container">
163
<input type="text" id="search-input" placeholder="Search Docker Hub">
164
<button id="search-button">
165
<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
166
<path d="M21 21L16.65 16.65M19 11C19 15.4183 15.4183 19 11 19C6.58172 19 3 15.4183 3 11C3 6.58172 6.58172 3 11 3C15.4183 3 19 6.58172 19 11Z" stroke="white" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
167
</svg>
168
</button>
169
</div>
170
<script>
171
function performSearch() {
172
const query = document.getElementById('search-input').value;
173
if (query) {
174
window.location.href = '/search?q=' + encodeURIComponent(query);
175
}
176
}
177
178
document.getElementById('search-button').addEventListener('click', performSearch);
179
document.getElementById('search-input').addEventListener('keypress', function(event) {
180
if (event.key === 'Enter') {
181
performSearch();
182
}
183
});
184
</script>
185
</body>
186
</html>
187
`;
188
return text;
189
}
190
191
export default {
192
async fetch(request, env, ctx) {
193
const getReqHeader = (key) => request.headers.get(key); // 获取请求头
194
195
let url = new URL(request.url); // 解析请求URL
196
const userAgentHeader = request.headers.get('User-Agent');
197
const userAgent = userAgentHeader ? userAgentHeader.toLowerCase() : "null";
198
if (env.UA) 屏蔽爬虫UA = 屏蔽爬虫UA.concat(await ADD(env.UA));
199
workers_url = `https://${url.hostname}`;
200
const pathname = url.pathname;
201
202
// 获取请求参数中的 ns
203
const ns = url.searchParams.get('ns');
204
const hostname = url.searchParams.get('hubhost') || url.hostname;
205
const hostTop = hostname.split('.')[0]; // 获取主机名的第一部分
206
207
let checkHost; // 在这里定义 checkHost 变量
208
// 如果存在 ns 参数,优先使用它来确定 hub_host
209
if (ns) {
210
if (ns === 'docker.io') {
211
hub_host = 'registry-1.docker.io'; // 设置上游地址为 registry-1.docker.io
212
} else {
213
hub_host = ns; // 直接使用 ns 作为 hub_host
214
}
215
} else {
216
checkHost = routeByHosts(hostTop);
217
hub_host = checkHost[0]; // 获取上游地址
218
}
219
220
const fakePage = checkHost ? checkHost[1] : false; // 确保 fakePage 不为 undefined
221
console.log(`域名头部: ${hostTop}\n反代地址: ${hub_host}\n伪装首页: ${fakePage}`);
222
const isUuid = isUUID(pathname.split('/')[1].split('/')[0]);
223
224
if (屏蔽爬虫UA.some(fxxk => userAgent.includes(fxxk)) && 屏蔽爬虫UA.length > 0) {
225
// 首页改成一个nginx伪装页
226
return new Response(await nginx(), {
227
headers: {
228
'Content-Type': 'text/html; charset=UTF-8',
229
},
230
});
231
}
232
233
const conditions = [
234
isUuid,
235
pathname.includes('/_'),
236
pathname.includes('/r/'),
237
pathname.includes('/v2/repositories'),
238
pathname.includes('/v2/user'),
239
pathname.includes('/v2/orgs'),
240
pathname.includes('/v2/_catalog'),
241
pathname.includes('/v2/categories'),
242
pathname.includes('/v2/feature-flags'),
243
pathname.includes('search'),
244
pathname.includes('source'),
245
pathname == '/',
246
pathname == '/favicon.ico',
247
pathname == '/auth/profile',
248
];
249
250
if (conditions.some(condition => condition) && (fakePage === true || hostTop == 'docker')) {
251
if (env.URL302) {
252
return Response.redirect(env.URL302, 302);
253
} else if (env.URL) {
254
if (env.URL.toLowerCase() == 'nginx') {
255
//首页改成一个nginx伪装页
256
return new Response(await nginx(), {
257
headers: {
258
'Content-Type': 'text/html; charset=UTF-8',
259
},
260
});
261
} else return fetch(new Request(env.URL, request));
262
} else if (url.pathname == '/'){
263
return new Response(await searchInterface(), {
264
headers: {
265
'Content-Type': 'text/html; charset=UTF-8',
266
},
267
});
268
}
269
270
const newUrl = new URL("https://registry.hub.docker.com" + pathname + url.search);
271
272
// 复制原始请求的标头
273
const headers = new Headers(request.headers);
274
275
// 确保 Host 头部被替换为 hub.docker.com
276
headers.set('Host', 'registry.hub.docker.com');
277
278
const newRequest = new Request(newUrl, {
279
method: request.method,
280
headers: headers,
281
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.blob() : null,
282
redirect: 'follow'
283
});
284
285
return fetch(newRequest);
286
}
287
288
// 修改包含 %2F 和 %3A 的请求
289
if (!/%2F/.test(url.search) && /%3A/.test(url.toString())) {
290
let modifiedUrl = url.toString().replace(/%3A(?=.*?&)/, '%3Alibrary%2F');
291
url = new URL(modifiedUrl);
292
console.log(`handle_url: ${url}`);
293
}
294
295
// 处理token请求
296
if (url.pathname.includes('/token')) {
297
let token_parameter = {
298
headers: {
299
'Host': 'auth.docker.io',
300
'User-Agent': getReqHeader("User-Agent"),
301
'Accept': getReqHeader("Accept"),
302
'Accept-Language': getReqHeader("Accept-Language"),
303
'Accept-Encoding': getReqHeader("Accept-Encoding"),
304
'Connection': 'keep-alive',
305
'Cache-Control': 'max-age=0'
306
}
307
};
308
let token_url = auth_url + url.pathname + url.search;
309
return fetch(new Request(token_url, request), token_parameter);
310
}
311
312
// 修改 /v2/ 请求路径
313
if ( hub_host == 'registry-1.docker.io' && /^\/v2\/[^/]+\/[^/]+\/[^/]+$/.test(url.pathname) && !/^\/v2\/library/.test(url.pathname)) {
314
//url.pathname = url.pathname.replace(/\/v2\//, '/v2/library/');
315
url.pathname = '/v2/library/' + url.pathname.split('/v2/')[1];
316
console.log(`modified_url: ${url.pathname}`);
317
}
318
319
// 更改请求的主机名
320
url.hostname = hub_host;
321
322
// 构造请求参数
323
let parameter = {
324
headers: {
325
'Host': hub_host,
326
'User-Agent': getReqHeader("User-Agent"),
327
'Accept': getReqHeader("Accept"),
328
'Accept-Language': getReqHeader("Accept-Language"),
329
'Accept-Encoding': getReqHeader("Accept-Encoding"),
330
'Connection': 'keep-alive',
331
'Cache-Control': 'max-age=0'
332
},
333
cacheTtl: 3600 // 缓存时间
334
};
335
336
// 添加Authorization头
337
if (request.headers.has("Authorization")) {
338
parameter.headers.Authorization = getReqHeader("Authorization");
339
}
340
341
// 发起请求并处理响应
342
let original_response = await fetch(new Request(url, request), parameter);
343
let original_response_clone = original_response.clone();
344
let original_text = original_response_clone.body;
345
let response_headers = original_response.headers;
346
let new_response_headers = new Headers(response_headers);
347
let status = original_response.status;
348
349
// 修改 Www-Authenticate 头
350
if (new_response_headers.get("Www-Authenticate")) {
351
let auth = new_response_headers.get("Www-Authenticate");
352
let re = new RegExp(auth_url, 'g');
353
new_response_headers.set("Www-Authenticate", response_headers.get("Www-Authenticate").replace(re, workers_url));
354
}
355
356
// 处理重定向
357
if (new_response_headers.get("Location")) {
358
return httpHandler(request, new_response_headers.get("Location"));
359
}
360
361
// 返回修改后的响应
362
let response = new Response(original_text, {
363
status,
364
headers: new_response_headers
365
});
366
return response;
367
}
368
};
369
370
/**
371
* 处理HTTP请求
372
* @param {Request} req 请求对象
373
* @param {string} pathname 请求路径
374
*/
375
function httpHandler(req, pathname) {
376
const reqHdrRaw = req.headers;
377
378
// 处理预检请求
379
if (req.method === 'OPTIONS' &&
380
reqHdrRaw.has('access-control-request-headers')
381
) {
382
return new Response(null, PREFLIGHT_INIT);
383
}
384
385
let rawLen = '';
386
387
const reqHdrNew = new Headers(reqHdrRaw);
388
389
const refer = reqHdrNew.get('referer');
390
391
let urlStr = pathname;
392
393
const urlObj = newUrl(urlStr);
394
395
/** @type {RequestInit} */
396
const reqInit = {
397
method: req.method,
398
headers: reqHdrNew,
399
redirect: 'follow',
400
body: req.body
401
};
402
return proxy(urlObj, reqInit, rawLen);
403
}
404
405
/**
406
* 代理请求
407
* @param {URL} urlObj URL对象
408
* @param {RequestInit} reqInit 请求初始化对象
409
* @param {string} rawLen 原始长度
410
*/
411
async function proxy(urlObj, reqInit, rawLen) {
412
const res = await fetch(urlObj.href, reqInit);
413
const resHdrOld = res.headers;
414
const resHdrNew = new Headers(resHdrOld);
415
416
// 验证长度
417
if (rawLen) {
418
const newLen = resHdrOld.get('content-length') || '';
419
const badLen = (rawLen !== newLen);
420
421
if (badLen) {
422
return makeRes(res.body, 400, {
423
'--error': `bad len: ${newLen}, except: ${rawLen}`,
424
'access-control-expose-headers': '--error',
425
});
426
}
427
}
428
const status = res.status;
429
resHdrNew.set('access-control-expose-headers', '*');
430
resHdrNew.set('access-control-allow-origin', '*');
431
resHdrNew.set('Cache-Control', 'max-age=1500');
432
433
// 删除不必要的头
434
resHdrNew.delete('content-security-policy');
435
resHdrNew.delete('content-security-policy-report-only');
436
resHdrNew.delete('clear-site-data');
437
438
return new Response(res.body, {
439
status,
440
headers: resHdrNew
441
});
442
}
443
444
async function ADD(envadd) {
445
var addtext = envadd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ','); // 将空格、双引号、单引号和换行符替换为逗号
446
if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
447
if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1);
448
const add = addtext.split(',');
449
return add;
450
}

11. 设置路由

回到worker页面,点击刚部署好的worker中,点击到设置页面,在域和路由栏上点击添加按钮。

default

12. 添加自定义域

default

添加完成后点击添加域保存。这里的域名是个二级域名,类似:dockerhub.xxxxx.xxx。

default

13. 查看域和路由

在上面的步骤添加完成之后,返回域和路由,可以看到添加的自定义域信息。

default

14. 访问域名

在自定义域名生效后,我们可以使用https://您的自定义域名 直接访问自己搭建的docker镜像源站。

default

当加载出来这个页面的时候,就说明我们已经配置好啦!

群晖配置docker镜像源

1. 设置镜像源

在 Container Manager中设置镜像源:

default

2. 使用镜像源

default

3. 搜索镜像

方式一:

在搜索的时候,有的时候搜索结果不是很准,尽量使用完整的名称搜索会好一点,然后你需要拉到第一页的最后几条,就能看到搜索的镜像了。

default

方式二:

使用SSH下载镜像。

假如Workers项目自定义域名为:docker.abc.com,在拉取镜像的时候,在官方镜像路径前面加你的自定义域名即可,如:docker pull docker.abc.com/stilleshan/frpc:latest

码字不易,感谢分享评论赞助。

本文标题:搭建自己的Docker镜像源
文章作者:Cirry
发布时间:2024-11-04
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode