Docker SDK for Python:如何使用自定义 Dockerfile 和自定义上下文构建映像

Mar*_*uri 5 python docker dockerfile

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

\n
docker build -f path/to/dockerfile/Dockerfile.name -t image:version path/to/context/.\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

目录结构如下:

\n
opt\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 project\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 dockerfile\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Dockerfile.name\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n\xe2\x94\x82       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 app\n\xe2\x94\x82           \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 target\n\xe2\x94\x82               \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 app-0.0.1-SNAPSHOT.jar\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 script.py\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

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

\n
    \n
  • path (str) \xe2\x80\x93 包含 Dockerfile 的目录的路径(我猜这是上下文)
  • \n
  • custom_context (bool) \xe2\x80\x93 如果使用 fileobj 则可选
  • \n
  • fileobj \xe2\x80\x93 用作 Dockerfile 的文件对象。(或类似文件的对象)
  • \n
\n

当我使用这样的方法时:

\n
client.images.build(\n    path = path_to_context,\n    fileobj=open(path_to_file, \'rb\'),\n    custom_context=True,\n    tag=\'image:version\'\n)\n
Run Code Online (Sandbox Code Playgroud)\n

我收到此错误:

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

Dockerfile的内容如下:

\n
FROM openjdk:16-alpine\nCOPY target/app-0.0.1-SNAPSHOT.jar app.jar\nCMD ["java", "-jar", "-Dspring.profiles.active=docker", "/app.jar"]\n
Run Code Online (Sandbox Code Playgroud)\n

但我猜测该错误不是由于该命令与 CLI 正确配合而导致的,它只是与 SDK 发生了冲突。

\n

难道我做错了什么?

\n

谢谢!

\n

编辑:

\n

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

\n
Traceback (most recent call last):\n  File "script.py", line 33, in <module>\n    client.images.build(\n  File "/Library/Python/3.8/site-packages/docker/models/images.py", line 287, in build\n    raise BuildError(chunk[\'error\'], result_stream)\ndocker.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\n
Run Code Online (Sandbox Code Playgroud)\n

cro*_*kap 2

我删除了custom_context=True,,问题就消失了。

编辑:

使用您的项目树:

import docker
client = docker.from_env()

client.images.build(
    path = './project/src/app/target/',
    dockerfile = '../../../Dockerfile/Dockerfile.name',
    tag='image:version',
)
Run Code Online (Sandbox Code Playgroud)