如何配置 DNS 缓存减少 registry 解析延迟

解读

在国内前端/Node 面试中,面试官问“如何配置 DNS 缓存减少 registry 解析延迟”并不是想听你背诵 /etc/hosts 写法,而是考察三点:

  1. 你是否意识到 npm install 的瓶颈往往卡在 TCP/TLS 握手前的 DNS 解析;
  2. 你是否能把“DNS 缓存”这一通用网络优化手段,落地到 npm 场景(registry 域名、scope 域名、proxy 域名);
  3. 你是否了解 企业内网、CI、Docker、Yarn/Bun 共存时的缓存一致性风险。
    回答时要先给出“可量化的延迟收益”,再给出“可落地的配置步骤”,最后补一句“灰度验证方案”,就能体现资深感。

知识点

  1. npm 域名列表:默认 registry 为 https://registry.npmjs.org,国内镜像 https://registry.npmmirror.com;带 scope 的包还会解析 @scope:registry 对应的域名;若走代理,还要解析代理服务器域名。
  2. DNS 缓存层级:浏览器→系统 stub→本地缓存服务(nscd、dnsmasq、systemd-resolved)→上游递归(114.114.114.114、阿里 223.5.5.5、腾讯云 183.60.83.19)→权威 DNS。
  3. 缓存 TTL 与 npm 的权衡:官方 registry 的 CNAME TTL 仅 60 s,意味着系统缓存 1 分钟就失效;国内镜像 TTL 通常 300 s;若盲目加大缓存,可能命中失效 IP,导致 404 或 SNI 错误。
  4. Node 层 DNS 缓存:Node ≥12.19 内置 dns.setDefaultResultOrder('ipv4first') 与 dns.setServers(['223.5.5.5','119.29.29.29']),但 无内置缓存,需依赖 dns-cache@1.0.2 或 global-agent@3.0.0 在内存里做 LRU。
  5. CI 与容器:GitHub Actions、GitLab Runner 每次起新容器,系统缓存为空;dnsmasq sidecar 或 docker run --dns=127.0.0.1 把缓存进程跟构建容器同生命周期,可让万行依赖安装时间从 3 min 降到 40 s。
  6. 安全审计:DNS 缓存投毒会导致 package.json 中的 tarball 地址被劫持到恶意服务器;因此企业内网必须开启 DNSSEC + DoT/DoH,并在 npm 侧配置 cafile 与 strict-ssl=true 做双保险。

答案

线上生产环境我采用“三层缓存 + 灰度验证”方案,把平均 DNS 解析耗时从 120 ms 降到 8 ms,安装 1.2 GB monorepo 提速 35%。

  1. 客户端层(Node 进程内)
    在 .npmrc 同级目录放置 dns-cache.js,内容:

    const dns = require('dns');
    const LRU = require('lru-cache');
    const cache = new LRU({ max: 200, ttl: 1000 * 30 });
    const orig = dns.lookup;
    dns.lookup = (host, opts, cb) => {
      const key = `${host}-${opts.family}`;
      if (cache.has(key)) return cb(null, ...cache.get(key));
      orig(host, opts, (err, addr, fam) => {
        if (!err) cache.set(key, [addr, fam]);
        cb(err, addr, fam);
      });
    };
    

    启动 npm 时注入:

    NODE_OPTIONS="--require ./dns-cache.js" npm ci
    
  2. 系统层(Linux 构建机)
    部署 dnsmasq,配置文件 /etc/dnsmasq.d/npm.conf:

    cache-size=1000
    neg-ttl=3600
    min-cache-ttl=300
    server=223.5.5.5
    server=180.76.76.76
    address=/registry.npmjs.org/104.16.27.35
    address=/registry.npmmirror.com/120.55.238.238
    

    把 127.0.0.1 写入 /etc/resolv.conf 首位,并 systemctl enable --now dnsmasq。

  3. 网络层(企业内网)
    在办公网核心交换机旁路部署 DNS 缓存服务器,开启 ECS (EDNS Client Subnet) 透传,保证返回就近 CDN 节点;同时把缓存 TTL 上限提到 10 min,并配置 DNSSEC 验证 防止缓存投毒。

  4. 灰度验证
    使用 npm install --timing 输出 dns:lookup 耗时;对比基线,若 95 分位 > 50 ms 则回滚;同时跑 npm audit 确保 tarball 哈希值未变。

  5. Docker 场景
    把 dnsmasq 作为 sidecar 容器 与构建容器共享网络命名空间,Dockerfile 最后阶段 COPY --from=builder 仅保留依赖产物,避免缓存污染镜像层。

通过以上配置,既利用了 本地 LRU 热缓存 又兼顾 系统级负缓存,在保持 npm 官方 registry 高可用前提下,把 DNS 解析延迟对 install 总耗时的占比从 18% 压到 2% 以内。

拓展思考

  1. HTTP Keep-Alive vs DNS 缓存:即使 DNS 缓存命中,若 TCP 每次新建连接仍要 3-RTT;可配合 .npmrc 中 fetch-retry-mintimeout=20000 与 maxsockets=16 复用连接,进一步降低延迟。
  2. 双 registry 故障转移:在 package.json 里用 publishConfig 指向主 registry,在 .npmrc 用 @company:registry=https://repo.mycompany.com 做 scope 级分流;当主 registry DNS 不可解析时,通过 dnsmasq bogus-nxdomain 触发 fallback 到镜像,实现 0 人工干预 的容灾。
  3. IPv6 优先级:国内部分 CDN 对 IPv6 解析返回 2400:3200::1 但 RTT 高于 IPv4;可在 dnsmasq 里 filter-AAAA 强制返回空,或 Node 层 dns.setDefaultResultOrder('ipv4first'),避免 Happy Eyeballs 超时。
  4. 可观测性:把 dns.lookup 耗时通过 opentelemetry-js 注入 trace,统一上报到 阿里云 SLS;当某个 registry 域名解析延迟突增 2 倍,自动触发 PagerDuty,比用户先发现“安装卡死”问题。