python - 适用于 Python 的 Docker SDK:如何使用自定义 Dockerfile 和自定义上下文构建映像
问题描述
我正在尝试使用 Docker SDK for Python 复制此命令:
docker build -f path/to/dockerfile/Dockerfile.name -t image:version path/to/context/.
path/to/dockerfile和path/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 一起工作。
从文档中,图像构建方法具有以下参数:
- path (str) – 包含 Dockerfile 的目录的路径(我猜这是上下文)
- custom_context (bool) -- 如果使用 fileobj,则可选
- fileobj – 用作 Dockerfile 的文件对象。(或类似文件的对象)
当我使用这样的方法时:
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
解决方案
即使文档提到“构建上下文 中 到 Dockerfile 的路径” ,如果指定了绝对路径,它也适用于构建上下文之外的 Dockerfile 。
使用我的项目树:
client.images.build(
path = '/opt/project/src/',
dockerfile = '/opt/project/dockerfile/Dockerfile.name',
tag = 'image:version'
)
推荐阅读
- java - Java 在 for 循环后跳过了我的一些代码
- python - 下载并解压 Zip 文件
- sql - 如何在具有共同一列的 Id 之间进行精确匹配?
- node.js - 客户端建立连接时 Socket.io 服务器没有响应
- python - 没有名为“bindsnet.network”的模块
- c# - .NET Core 3.1 中的 Cookie
- mysql - 如果第二个选择为空,如何忽略?
- java - 如何在 Maven 中停止所有这些详细的输出
- google-apps-script - 使用脚本在整个 Google Drive 文件夹、页眉、页脚、谷歌文档中查找和替换文本
- css - 在没有 Sass 的情况下更改 Bootstrap 4 排水沟