首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python将docker镜像发送到Docker hub并将其标记为最新版本

使用python将docker镜像发送到Docker hub并将其标记为最新版本
EN

Stack Overflow用户
提问于 2020-09-08 21:16:50
回答 1查看 50关注 0票数 0

我正在尝试将dokcer图像发送到我在docker hub中的帐户,并使用python标记它。

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

代码语言:javascript
复制
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中的帐户,并将其标记为最新版本。

EN

回答 1

Stack Overflow用户

发布于 2020-09-08 22:28:53

正如@DavidMaze提到的,你真的应该试着遵循并阅读他们的文档。

我--我的好奇心--几个月前也有同样的问题。我问自己是否有可能用Python来做这件事。但是,我不想坐下来等待回应,所以我在这里从来没有问过,我仔细阅读了他们的文档和源代码来完成它。

注意:此示例可能不起作用。把它作为你自己研究/实现的起点。欢迎对此答案进行编辑/评论!

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

代码语言:javascript
复制
"""
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["status"], 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

代码语言:javascript
复制
DOCKER_API_CLIENT.tag(
    image, "xxx/xxx(repository)", tag=latest
)

EDIT 2:链接

以下是我使用/编写的东西的官方链接。

我希望这对某些人有帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63794772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档