Docker专题-05 搭建镜像加速服务

Docker专题-05 搭建镜像加速服务

  • 本教程由羞涩梦整理同步发布,本人技术分享站点:blog.hukanfa.com
  • 转发本文请备注原文链接,本文内容整理日期:2024-06-19
  • csdn 博客名称:五维空间-影子,欢迎关注

  • 说明

    • 由于最新的政策管控,国内所有 DockerHub 镜像加速服务商都停止服务,急需替代方案
    • 本章将介绍如何通过Cloudflare 提供的免费 Worker 服务来搭建属于自己的镜像加速服务
    • 如需获取本人提供的加速域名请前往个人博客blog.hukanfa.com 阅读本文,也可自行按照下面步骤配置

1 前置准备

  • 操作如下
    • 注册新域名,如本人以自己名字在云厂商注册了.cn域名
    • 创建 Cloudflare账号
    # 官网地址,选择免费计划(Free Plans)即可
    https://dash.cloudflare.com/login
    

    image-20240618203604318

2 站点配置

  • 操作如下
    • 登录 Cloudflare 账号,进入到主页,点击网站,添加站点 xxx.cn

    image-20240618204618678

    • 激活站点:站点配置完成后,界面会显示对应区域名称服务器地址,然后更新新注册域名的ns地址稍等会即可自动检测激活

    image-20240618205033938

    image-20240618205247506

3 Workers配置

  • 操作如下
    • 回到 Cloudflare 主页,点击Workers 和 Pages,然后创建应用程序,命名如Hub, 按照提示点击完成即可

    image-20240618210029623

    • 创建完成后,点击hub进入到项目业中,再点击编辑代码,将代码替换为如下内容,并且保存即可

    image-20240619095917148

    image-20240619100018135

    'use strict'
    const hub_host = 'registry-1.docker.io'
    const auth_url = 'https://auth.docker.io'
    // 请将 hub.xxx.cn 替换为自己的域名
    const workers_url = 'https://hub.xxx.cn'
    const PREFLIGHT_INIT = {
      status: 204,
      headers: new Headers({
          'access-control-allow-origin': '*',
          'access-control-allow-methods': 'GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS',
          'access-control-max-age': '1728000',
      }),
    }
    function makeRes(body, status = 200, headers = {}) {
      headers['access-control-allow-origin'] = '*'
      return new Response(body, {status, headers})
    }
    function newUrl(urlStr) {
      try {
          return new URL(urlStr)
      } catch (err) {
          return null
      }
    }
    addEventListener('fetch', e => {
      const ret = fetchHandler(e)
          .catch(err => makeRes('cfworker error:\n' + err.stack, 502))
      e.respondWith(ret)
    })
    async function fetchHandler(e) {
    const getReqHeader = (key) => e.request.headers.get(key);
    let url = new URL(e.request.url);
    if (url.pathname === '/token') {
        let token_parameter = {
          headers: {
          'Host': 'auth.docker.io',
          'User-Agent': getReqHeader("User-Agent"),
          'Accept': getReqHeader("Accept"),
          'Accept-Language': getReqHeader("Accept-Language"),
          'Accept-Encoding': getReqHeader("Accept-Encoding"),
          'Connection': 'keep-alive',
          'Cache-Control': 'max-age=0'
          }
        };
        let token_url = auth_url + url.pathname + url.search
        return fetch(new Request(token_url, e.request), token_parameter)
    }
    url.hostname = hub_host;
    let parameter = {
      headers: {
        'Host': hub_host,
        'User-Agent': getReqHeader("User-Agent"),
        'Accept': getReqHeader("Accept"),
        'Accept-Language': getReqHeader("Accept-Language"),
        'Accept-Encoding': getReqHeader("Accept-Encoding"),
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0'
      },
      cacheTtl: 3600
    };
    if (e.request.headers.has("Authorization")) {
      parameter.headers.Authorization = getReqHeader("Authorization");
    }
    let original_response = await fetch(new Request(url, e.request), parameter)
    let original_response_clone = original_response.clone();
    let original_text = original_response_clone.body;
    let response_headers = original_response.headers;
    let new_response_headers = new Headers(response_headers);
    let status = original_response.status;
    if (new_response_headers.get("Www-Authenticate")) {
      let auth = new_response_headers.get("Www-Authenticate");
      let re = new RegExp(auth_url, 'g');
      new_response_headers.set("Www-Authenticate", response_headers.get("Www-Authenticate").replace(re, workers_url));
    }
    if (new_response_headers.get("Location")) {
      return httpHandler(e.request, new_response_headers.get("Location"))
    }
    let response = new Response(original_text, {
              status,
              headers: new_response_headers
          })
    return response;
    }
    function httpHandler(req, pathname) {
      const reqHdrRaw = req.headers
      // preflight
      if (req.method === 'OPTIONS' &&
          reqHdrRaw.has('access-control-request-headers')
      ) {
          return new Response(null, PREFLIGHT_INIT)
      }
      let rawLen = ''
      const reqHdrNew = new Headers(reqHdrRaw)
      const refer = reqHdrNew.get('referer')
      let urlStr = pathname
      const urlObj = newUrl(urlStr)
      /** @type {RequestInit} */
      const reqInit = {
          method: req.method,
          headers: reqHdrNew,
          redirect: 'follow',
          body: req.body
      }
      return proxy(urlObj, reqInit, rawLen, 0)
    }
    async function proxy(urlObj, reqInit, rawLen) {
      const res = await fetch(urlObj.href, reqInit)
      const resHdrOld = res.headers
      const resHdrNew = new Headers(resHdrOld)
      // verify
      if (rawLen) {
          const newLen = resHdrOld.get('content-length') || ''
          const badLen = (rawLen !== newLen)
          if (badLen) {
              return makeRes(res.body, 400, {
                  '--error': `bad len: {newLen}, except:{rawLen}`,
                  'access-control-expose-headers': '--error',
              })
          }
      }
      const status = res.status
      resHdrNew.set('access-control-expose-headers', '*')
      resHdrNew.set('access-control-allow-origin', '*')
      resHdrNew.set('Cache-Control', 'max-age=1500')
      resHdrNew.delete('content-security-policy')
      resHdrNew.delete('content-security-policy-report-only')
      resHdrNew.delete('clear-site-data')
      return new Response(res.body, {
          status,
          headers: resHdrNew
      })
    }
    
    • 点击右上角的部署即可完成部署,然后回到 hub 项目页,点击设置,点击触发器,再点击添加路由
    # 输入 hub.xxx.cn/* 路由(注意末尾的/*是不可缺少的),区域选择前面添加的 xxx.cn 即可
    

    image-20240619100430389

4 Dns解析

  • 操作如下
    • 回到 Cloudflare主页,点击前面添加的xxx.cn域名,点击设置,点击DNS,点击添加A记录
    设置名称为hub,地址为8.8.8.8(随意填),但是一定要启用代理
    

    • 配置完成后,执行下述命令验证站点是否正常拉取如nginx:latest镜像
    # 官方
    docker pull docker.io/library/nginx:latest
    # 自建
    docker pull hub.hukanfa.cn/library/nginx:latest
    # 最后可将该域名配置到 /etc/docker/daemon.json 文件中作为镜像加速器
    {
    "registry-mirrors": ["https://hub.hukanfa.cn"],
    "exec-opts": ["native.cgroupdriver=systemd"],
    "live-restore":true,
    "log-driver": "json-file",
    "log-opts": {
    "max-size": "100m",
    "max-file": "3"
    },
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 10
    }
    # 重载配置并重启docker
    systemctl daemon-reload
    systemctl restart docker