首页 > 解决方案 > 如何使用 Docker Registry HTTP API V2 获取 docker 注册表中所有存储库的列表?

问题描述

与我合作的一个外部组织允许我访问私有(受身份验证令牌保护)docker 注册表,最终我希望能够使用 docker 的 HTTP API V2 查询此注册表,以获得所有注册表中可用的存储库和/或图像。

但在此之前,我首先想获得一些基本练习,即在Docker Hub等公共注册表上构建这些类型的 API 查询。所以我继续在 Docker Hub 上注册了自己的用户名和密码,还查阅了 API V2 文档,其中指出可以请求API 版本检查

GET /v2/

或请求存储库列表

GET /v2/_catalog

使用 curl 以及我用来注册 Docker Hub 帐户的用户名和密码,我尝试在命令行构造一个 GET 请求:

stachyra> curl -u stachyra:<my_password> -X GET https://index.docker.io/v2/
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
stachyra> curl -u stachyra:<my_password> -X GET https://index.docker.io/v2/_catalog
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":[{"Type":"registry","Class":"","Name":"catalog","Action":"*"}]}]}

当然,<my_password>我用我的实际帐户密码代替了 。

我一直期待从这个查询中得到的响应是一条巨大的 json 消息,其中列出了数千个存储库名称,但似乎 API 拒绝了我的 Docker Hub 凭据。

问题 1:我什至有index.docker.iodocker hub 注册表的正确 URL ( ) 吗?(我首先根据命令行工具返回的状态信息做出了这个假设docker info,所以我有充分的理由认为它是正确的。)

问题 2:假设我有注册服务本身的正确 URL,为什么我的查询返回“未授权”错误代码?当我尝试通过网络登录 hub.docker.com 时,我的帐户凭据工作正常,那么这两种情况有什么区别?

标签: restdockerrestful-authenticationdockerhubdocker-api

解决方案


Here is an example program to read repositories from a registry. I used it as a learning aid with Docker Hub.

#!/bin/bash

set -e

# set username and password
UNAME="username"
UPASS="password"

# get token to be able to talk to Docker Hub
TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${UNAME}'", "password": "'${UPASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)

# get list of repos for that user account
REPO_LIST=$(curl -s -H "Authorization: JWT ${TOKEN}" 
https://hub.docker.com/v2/repositories/${UNAME}/?page_size=10000 | jq -r '.results|.[]|.name')

# build a list of all images & tags
for i in ${REPO_LIST}
do
  # get tags for repo
  IMAGE_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" 
  https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/?page_size=10000 | jq -r '.results|.[]|.name')

  # build a list of images from tags
  for j in ${IMAGE_TAGS}
  do
    # add each tag to list
    FULL_IMAGE_LIST="${FULL_IMAGE_LIST} ${UNAME}/${i}:${j}"
  done
done

# output list of all docker images
for i in ${FULL_IMAGE_LIST}
do
  echo ${i}
done

(this comes from an article on Docker site that describes how to use the API.)

In essence...

  • get a token
  • pass the token as a header Authorization: JWT <token> with any API calls you make
  • the api call you want to use to list repositories is https://hub.docker.com/v2/repositories/<username>/

推荐阅读