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

使用Python Docker SDK构建镜像时COPY文件失败,如何确保文件在构建上下文?

COPY Failed When Using Python Docker SDK (Works with Docker CLI)

The Problem

I've got this file structure:

Dockerfile
apps/
└── myapi/
    └── api-1.0.8.json

Here's my Dockerfile:

FROM mybase
# Simply need to update config file
ARG asset_api=myapi
ARG asset_api_version=1.0.8
COPY $PWD/apps/${asset_api}/api-${asset_api_version}.json /api.json

Building with the Docker CLI works perfectly fine, but when I run my Python Docker SDK code:

client.images.build(path="./", tag='myimage:tag', buildargs={'asset_api': 'myapi', 'asset_api_version': '1.0.8'}, use_config_proxy=True)

I hit this error:

docker.errors.BuildError: COPY failed: stat /var/lib/docker/tmp/docker-builder289614590/apps/myapi/api-1.0.8.json: no such file or directory

How can I make sure the file is properly included in the build context?

The Fix

The issue is that you're using $PWD in your Dockerfile's COPY command—and that's a mistake, even if it seemed to work with the CLI. Here's why and how to fix it:

Why This Breaks with the SDK

When you run a Docker build, Docker sends your entire build context (in this case, the current directory ./) to the Docker daemon, which runs the build in a temporary directory on its end.

  • With the CLI, your local shell might be expanding $PWD to your local working directory before sending the Dockerfile to the daemon. That's why it worked by accident.
  • With the Python SDK, the $PWD variable gets passed directly to the daemon, where it resolves to the daemon's temporary build directory (like /var/lib/docker/tmp/docker-builder...). Since your apps folder isn't in that directory, the COPY fails.

The Correct Dockerfile

Remove the $PWD prefix—Docker COPY paths are always relative to the root of your build context:

FROM mybase
# Simply need to update config file
ARG asset_api=myapi
ARG asset_api_version=1.0.8
COPY apps/${asset_api}/api-${asset_api_version}.json /api.json

Quick Checks to Ensure It Works

  1. Double-check that your Python script is running from the same directory that contains the Dockerfile and apps folder. You can verify this with:
    import os
    print(os.getcwd()) # Should output the path to your project root
    
  2. Make sure there are no typos in your build args or file paths—even a single character mismatch will cause this error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:30:19