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

构建Docker镜像时出现can't start new thread错误

Docker构建时pip安装报错:RuntimeError: can't start new thread

问题详情

  • 环境信息:
    • Docker版本:20.10.21,构建版本baeda1f
    • 宿主机:Ubuntu 18.04.6 LTS(GNU/Linux 5.4.0-1109-azure x86_64)
  • 错误现象:执行任意pip install命令均触发线程启动失败错误:

    File "/usr/local/lib/python3.9/threading.py", line 899, in start
    _start_new_thread(self._bootstrap, ())
    RuntimeError: can't start new thread

  • 涉及Dockerfile:
    FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
    RUN pip install aiohttp==3.6.2
    

解决方案

1. 修改pip安装参数,禁用多线程

pip默认开启多线程并行安装,容易触发容器内线程数限制,强制单线程安装:

RUN pip install --no-cache-dir --disable-pip-version-check --no-use-pep517 aiohttp==3.6.2

或者直接指定编译时单线程:

RUN pip install --no-cache-dir --build-option "--single-threaded" aiohttp==3.6.2

2. 调整宿主机与Docker的线程数限制

  • 查看当前宿主机线程数限制:
    ulimit -u
    
    临时调整为更高值(如4096):
    ulimit -u 4096
    
    永久调整需编辑/etc/security/limits.conf,添加:
    * soft nproc 4096
    * hard nproc 4096
    
  • 配置Docker daemon默认线程限制,编辑/etc/docker/daemon.json(无则创建):
    {
      "default-ulimits": {
        "nproc": {
          "hard": 4096,
          "soft": 4096
        }
      }
    }
    
    重启Docker服务生效:
    systemctl restart docker
    

3. 更换基础镜像并补充依赖

tiangolo的镜像可能存在隐性资源限制,换用官方Python基础镜像,同时补充aiohttp编译所需依赖:

FROM python:3.9-slim
RUN apt-get update && apt-get install -y --no-install-recommends gcc libssl-dev && \
    pip install --no-cache-dir aiohttp==3.6.2 && \
    apt-get purge -y gcc libssl-dev && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*

4. 检查Azure虚拟机规格

低配Azure虚拟机(如B1s、B1ms)的CPU和线程配额有限,尝试升级虚拟机规格,提升可用资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:25:23