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

如何在Dockerfile中正确执行requirements.txt内的GitHub仓库克隆命令

解决Docker中通过requirements.txt克隆GitHub仓库的问题

Got it, let's break down why your initial git clone git@github.com:USERNAME/REPO.git attempt failed and how to get your requirements.txt setup working smoothly in Docker.

核心问题分析

Your original git@ SSH clone failed because Docker containers don't automatically have access to your local GitHub SSH keys. Plus, many base Python images don't come with Git pre-installed—which is required for pip to handle Git-based dependencies.

方案1:直接用requirements.txt里的HTTP链接(最简单,适用于公开仓库)

If your repo is public, this is the easiest path. Here's what to add to your Dockerfile:

  1. Install Git first (most slim Python images skip it to save space):

    # 适用于Debian/Ubuntu系镜像(比如python:3.x-slim)
    RUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/*
    
    # 适用于Alpine系镜像(比如python:3.x-alpine)
    RUN apk add --no-cache git
    

    加上--no-install-recommends和rm -rf /var/lib/apt/lists/*是为了避免镜像体积膨胀。

  2. 正常执行pip安装
    Pip会自动处理requirements.txt里的Git仓库克隆,不需要额外操作:

    RUN pip install -r requirements.txt
    

    你原来的requirements.txt行-e git://github.com/USERNAME/REPO.git直接就能用,公开仓库不需要修改。

方案2:用SSH链接(适用于私有仓库)

如果你的仓库是私有,想用SSH替代HTTP,需要把SSH密钥安全地传入容器——绝对不要把私钥硬编码进Dockerfile,用构建参数更安全:

  1. 安装Git和SSH客户端

    # Debian/Ubuntu系
    RUN apt-get update && apt-get install -y --no-install-recommends git openssh-client && rm -rf /var/lib/apt/lists/*
    
    # Alpine系
    RUN apk add --no-cache git openssh-client
    
  2. 通过构建参数配置SSH
    在Dockerfile里添加这些步骤,安全配置SSH环境:

    # 创建SSH目录并设置权限(SSH对权限要求很严格)
    RUN mkdir -p /root/.ssh && chmod 700 /root/.ssh
    
    # 将GitHub加入已知主机,避免首次连接的确认提示
    RUN ssh-keyscan github.com >> /root/.ssh/known_hosts && chmod 644 /root/.ssh/known_hosts
    
    # 接收SSH私钥作为构建参数
    ARG SSH_PRIVATE_KEY
    RUN echo "$SSH_PRIVATE_KEY" > /root/.ssh/id_rsa && chmod 600 /root/.ssh/id_rsa
    
  3. 修改requirements.txt(如果需要)
    把仓库链接改成SSH格式:

    -e git@github.com:USERNAME/REPO.git
    
  4. 携带SSH密钥构建镜像
    构建时把本地SSH私钥作为参数传入:

    docker build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" -t your-image-name .
    
  5. 执行pip安装
    同样执行这条命令即可:

    RUN pip install -r requirements.txt
    

额外提示

  • requirements.txt里的-e(可编辑模式)主要用于本地开发时修改代码实时生效,但在Docker里作用不大,除非你挂载了本地代码卷。如果不需要可编辑模式,可以去掉-e简化配置。
  • 私有仓库用HTTP的话,也可以用个人访问令牌(PAT)拼接在URL里:https://<PAT>@github.com/USERNAME/REPO.git,但SSH是更安全的长期方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:02:13