首页 > 解决方案 > 适用于 Python 的 Docker SDK:如何使用自定义 Dockerfile 和自定义上下文构建映像

问题描述

我正在尝试使用 Docker SDK for Python 复制此命令:

docker build -f path/to/dockerfile/Dockerfile.name -t image:version path/to/context/.

path/to/dockerfilepath/to/context是不同的路径,即: /opt/project/dockerfile/opt/project/src/app/。

目录结构如下:

opt
├── project
│   ├── dockerfile
│   │   └── Dockerfile.name
│   └── src
│       └── app
│           └── target
│               └── app-0.0.1-SNAPSHOT.jar
└── script.py

该命令在 CLI 中正常工作,但我无法使其与 SDK 一起工作。

文档中,图像构建方法具有以下参数:

当我使用这样的方法时:

client.images.build(
    path = path_to_context,
    fileobj=open(path_to_file, 'rb'),
    custom_context=True,
    tag='image:version'
)

我收到此错误:

Traceback (most recent call last):
  File "script.py", line 33, in <module>
    client.images.build(
  File "/Library/Python/3.8/site-packages/docker/models/images.py", line 298, in build
    raise BuildError(last_event or 'Unknown', result_stream)
docker.errors.BuildError: {'message': 'unexpected EOF'}

Dockerfile 的内容如下:

FROM openjdk:16-alpine
COPY target/app-0.0.1-SNAPSHOT.jar app.jar
CMD ["java", "-jar", "-Dspring.profiles.active=docker", "/app.jar"]

但我猜这个错误不是因为该命令可以正确地与 CLI 一起工作,它只是破坏了 SDK。

难道我做错了什么?

谢谢!

编辑:

简单地删除custom_context=True并不能解决问题,因为上下文和构建路径不同。事实上,它会导致另一个错误,相对于文件在当前路径中不存在的事实:

Traceback (most recent call last):
  File "script.py", line 33, in <module>
    client.images.build(
  File "/Library/Python/3.8/site-packages/docker/models/images.py", line 287, in build
    raise BuildError(chunk['error'], result_stream)
docker.errors.BuildError: COPY failed: file not found in build context or excluded by .dockerignore: stat target/app-0.0.1-SNAPSHOT.jar: file does not exist

标签: pythondockerdockerfile

解决方案


即使文档提到“构建上下文 到 Dockerfile 的路径” ,如果指定了绝对路径,它也适用于构建上下文之外的 Dockerfile 。

使用我的项目树:

client.images.build(
    path = '/opt/project/src/',
    dockerfile = '/opt/project/dockerfile/Dockerfile.name',
    tag = 'image:version'
)

推荐阅读