【问题标题】:How to build local docker image using python API with custom tag name如何使用带有自定义标签名称的 python API 构建本地 docker 映像
【发布时间】:2019-12-18 10:56:33
【问题描述】:

我有这个脚本:

import docker
import os

localtag = "mypersonaltag"

client = docker.from_env()
dockerfile_path = os.path.dirname(os.getcwd())
print(dockerfile_path)

fname = dockerfile_path + "/Dockerfile"
path = os.path.dirname(fname)
image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag='localtag', rm=True)
print(image)

如果我执行这个脚本,它会创建并构建本地 docker 镜像,标签名称为 localtag,但不是 我的个人标签。我已经尝试了所有其他可能的方式,如下所示,看看标签参数。它抛出错误。

image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)


image, build_log = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag={localtag}, rm=True)

但奇怪的是,这个[image, build_log = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)] 命令可以通过 python 编辑器完美运行,而使用 python 脚本会出错。不知道为什么?但是,只要我在标签周围加上引号,正在破坏的 python 脚本现在就可以正常工作了。

>>> tag  = "test02"
>>> image, build_log  = client.images.build(path=path, dockerfile='Dockerfile', tag=tag, rm=True)
>>> print(image)
<Image: 'local_tag:latest', 'localtag:latest', 'test01:latest', 'test02:latest'>

【问题讨论】:

    标签: python docker docker-api


    【解决方案1】:
    image, build_log  = client.images.build(path=dockerfile_path, dockerfile='Dockerfile', tag=localtag, rm=True)
    

    将变量传递给函数的问题,删除localtag周围的引号

    如果你以这种方式传递变量tag={localtag},那么你就是在告诉 python:“嘿,可以变量,把它放在集合中,然后把这个集合传递给函数”。可能你会尝试使用 fstring 构造的f"{localtag}"(需要 python3.6)。

    --edit--

    请告诉我们,你如何调用你的脚本?错误是什么?

    【讨论】:

    • 如果您查看我的问题,我在脚本中尝试了这个,它不起作用或不喜欢我的标签周围的引号。不带引号它可以正常工作,带引号它会抱怨“requests.exceptions.ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))” 但很奇怪,如果我在 python 编辑器中运行命令它可以工作喜欢魅力,>>>标签=“test02”>>>图像,build_log = client.images.build(路径=路径,dockerfile='Dockerfile',标签=标签,rm=True)>>>打印(图像)所以,不知道为什么它在编辑器中有效。
    • tag=localtag|{localtag} - 这个结构非常非常奇怪
    • 现在我明白了,你的困惑“|”这意味着我尝试了不带引号和大括号的两个选项。但更奇怪的是它在 python 编辑器中可以正常工作,但不能通过脚本。我会更新问题。
    • 它也不起作用。请看下面,我正在使用python scriptname.py 调用python 脚本,我得到的错误是File "/usr/local/lib/python2.7/site-packages/requests/adapters.py", line 498, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer')),我的python 版本是2.7,所以没有fstring 选项。所以有些东西告诉我带引号的标签给了我脚本中的问题。
    • 首先,我强烈建议您切换到python3(不推荐使用python2)。第二个给我看你的docker-py 包的版本 - 它可能看起来像你的版本docker-py 中的错误:github.com/docker/docker-py/issues/978
    猜你喜欢
    • 2015-11-20
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多