微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将Docker映像发送到Docker Hub并使用python将其标记为最新

如何解决将Docker映像发送到Docker Hub并使用python将其标记为最新

我正在尝试将doccer图像发送到docker hub中的帐户并使用python对其进行标记

这是我到目前为止所取得的成就:

import docker

client = docker.from_env()
img = client.images.pull('Nginx:latest')
contanier = client.containers.run(img,detach=True,ports={'80/tcp': 8080})
# Here I am trying to send the image to my account (docker hub account) and tag it as the latest 

我正在努力寻找一种方法,将映像发送到docker hub中的帐户并将其标记为最新版本。

解决方法

正如@DavidMaze所述,您应该真正尝试阅读并阅读其文档。

我-出于好奇-几个月前有同样的问题。我问自己是否可以用Python做到这一点。但是,我不想坐着等待答复,所以我从没问过这个问题,因此我仔细阅读了他们的文档和源代码以完成任务。

注意:此示例可能不起作用。将其作为您自己的研究/实施的起点。欢迎编辑/评论此答案!

免责声明::这是对my very own experimentation结果的快速而肮脏的复制/清除。

"""
An example which shows how to push images to a docker registry
using the docker module.

Before starting,you will need a `.env` file with the following:

::

    OUR_DOCKER_USERNAME=Unknown
    OUR_DOCKER_PASSWORD=Unknown
    OUR_DOCKER_EMAIL=Unknown

Author:
    - @funilrys
"""

import logging
import os

import docker
from dotenv import load_dotenv

DOCKER_API_CLIENT = docker.APIClient(base_url="unix://var/run/docker.sock")

REGISTRY = "docker.io"

# WARNING: We assume that you tagged your images correctly!!!
# It should be formatted like `user/repository` as per Docker Hub!!
IMAGE_TAG_NAME = "nginx"

# Let's load the `.env` file.
load_dotenv(".env")


def log_response(response: dict) -> None:
    """
    Given a response from the Docker client.
    We log it.

    :raise Exception:
        When an error is caught.
    """

    if "stream" in response:
        for line in response["stream"].splitlines():
            if line:
                logging.info(line)

    if "progressDetail" in response and "status" in response:
        if "id" in response and response["progressDetail"]:
            percentage = round(
                (response["progressDetail"]["current"] * 100)
                / response["progressDetail"]["total"],2,)

            logging.info(
                "%s (%s): %s/%s (%s%%)",response["status"],response["id"],response["progressDetail"]["current"],response["progressDetail"]["total"],percentage,)
        elif "id" in response:
            logging.info("%s (%s)",response["id"])
        else:
            logging.info("%s",response["status"])
    elif "errorDetail" in response and response["errorDetail"]:
        raise Exception(response["errorDetail"]["message"])
    elif "status" in response:
        logging.info("%s",response["status"])


def get_credentials_from_env() -> dict:
    """
    Try to get the credentials from the environment variables.

    :return:
        {
            "username": str,"password": str,"email": str
        }
    """

    var2env: dict = {
        "username": "OUR_DOCKER_USERNAME","password": "OUR_DOCKER_PASSWORD","email": "OUR_DOCKER_EMAIL",}

    return {k: os.getenv(v,None) for k,v in var2env.items()}


def push_images(images: list,creds: dict) -> None:
    """
    Given credentials and a list of images to push,push the
    image to the declared registry.

    :param creds:
        The credentials to use.

    :param images:
        A list of images to push.
    """

    for image in images:
        for tag in image["RepoTags"]:
            publisher = DOCKER_API_CLIENT.push(
                repository=f"{REGISTRY}/{tag}",stream=True,decode=True,auth_config=creds,)

            for response in publisher:
                log_response(response)


if __name__ == "__main__":

    logging.basicConfig(level=logging.INFO,format="%(levelname)s: %(message)s")
    credentials = get_credentials_from_env()

    login = DOCKER_API_CLIENT.login(
        credentials["username"],password=credentials["password"],email=credentials["password"],registry=REGISTRY,reauth=True,)

    push_images(DOCKER_API_CLIENT.images(name=IMAGE_TAG_NAME),credentials)

编辑1:我忘记了您的标记部分:-)

这里是如何将图像标记为latest

DOCKER_API_CLIENT.tag(
    image,"xxx/xxx(repository)",tag=latest
)

编辑2:链接

这是我使用/写过的东西的官方链接。

我希望这对某人有帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?