You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Cloudinary图片上传出现Socket连接超时问题求助

Docker化Node.js应用上传Cloudinary间歇性Socket连接超时问题

问题现象

Docker化的Node.js应用上传图片至Cloudinary时,间歇性触发ERR_SOCKET_CONNECTION_TIMEOUT(Socket连接超时)错误,上传操作时好时坏。已确认服务器网络状况正常,错误集中出现在调用cloudinary.api.ping()环节。

错误栈信息

Error [ERR_SOCKET_CONNECTION_TIMEOUT]: Socket connection timeout 
 {
   error: Error [ERR_SOCKET_CONNECTION_TIMEOUT]: Socket connection timeout
       at new NodeError (node:internal/errors:399:5)
       at internalConnectMultiple (node:net:1099:20)
       at Timeout.internalConnectMultipleTimeout (node:net:1638:3)
       at listOnTimeout (node:internal/timers:575:11)
       at process.processTimers (node:internal/timers:514:7) {
     code: 'ERR_SOCKET_CONNECTION_TIMEOUT'
   }
 }

相关代码

const addProduct = async (req: Request, res: Response, next: NextFunction) => {
  const {
    title,
    snippet,
    description,
    quantity,
    price,
    coverImage,
    imageArray,
    category,
  } = req.body;
  try {
    cloudinary.api
      .ping()
      .then((res) => {
        console.log(`Cloudinary connection ${res.status}`);
      })
      .catch((err) => console.log(err));

    const imageUrlArray: Array<imageObjectType> = [];
    const coverImageUpload = await cloudinary.uploader.upload(coverImage);
    if (imageArray !== undefined) {
      for (let i = 0; i < imageArray.length; i++) {
        const image = await cloudinary.uploader.upload(imageArray[i]);
        imageUrlArray.push({
          publicId: image.public_id,
          secureUrl: image.secure_url,
        });
      }
    }
    console.log(req.seller);
    const product = await Product.create({
      title: title,
      snippet: snippet,
      description: description,
      quantity: quantity,
      price: price,
      coverImage: {
        publicId: coverImageUpload.public_id,
        secureUrl: coverImageUpload.secure_url,
      },
      imageArray: imageUrlArray,
      category: category,
      sellerId: req.seller,
    });
    console.log(product);
    if (product) {
      res.status(200).json({
        message: "Product added",
        category: category,
      });
    }
  } catch (err) {
    console.log(err);
  }
};

排查与解决方案

  • 移除冗余的ping检查:cloudinary.api.ping()是独立异步请求,未等待结果就执行后续上传,额外增加了网络连接次数。Cloudinary上传接口本身会处理连接状态,直接删除这段代码即可减少超时概率。

  • 调整Cloudinary超时配置:初始化Cloudinary客户端时显式设置更长的超时时间,适配Docker环境下的网络延迟:

    cloudinary.config({
      cloud_name: '你的云名称',
      api_key: '你的API密钥',
      api_secret: '你的API密钥',
      timeout: 30000 // 设置30秒超时,可根据实际情况调整
    });
    
  • 优化Docker网络配置:

    • 确保容器DNS配置正确,可在启动命令或docker-compose.yml中指定公共DNS(如8.8.8.8);
    • 若Cloudinary对IPv6支持不佳,可在Docker配置中禁用IPv6。
  • 添加上传重试机制:针对间歇性网络波动,对上传操作增加重试逻辑:

    const uploadWithRetry = async (image: string, retries = 3) => {
      try {
        return await cloudinary.uploader.upload(image);
      } catch (err) {
        if (retries > 0 && (err as any).code === 'ERR_SOCKET_CONNECTION_TIMEOUT') {
          console.log(`上传失败,剩余重试次数:${retries - 1}`);
          return uploadWithRetry(image, retries - 1);
        }
        throw err;
      }
    };
    
    // 替换原上传调用
    const coverImageUpload = await uploadWithRetry(coverImage);
    

内容的提问来源于stack exchange,提问作者Sumer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:35:35