使用Python Docker SDK构建镜像时COPY文件失败,如何确保文件在构建上下文?
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
$PWDto your local working directory before sending the Dockerfile to the daemon. That's why it worked by accident. - With the Python SDK, the
$PWDvariable gets passed directly to the daemon, where it resolves to the daemon's temporary build directory (like/var/lib/docker/tmp/docker-builder...). Since yourappsfolder 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
- Double-check that your Python script is running from the same directory that contains the Dockerfile and
appsfolder. You can verify this with:import os print(os.getcwd()) # Should output the path to your project root - 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

