Ответ 1
Насколько я знаю, CLI не позволяет искать/перечислять теги в репозитории.
Но если вы знаете, какой тег вы хотите, вы можете вывести это явно, добавив двоеточие и имя изображения: docker pull ubuntu:saucy
Я пытаюсь найти один конкретный тег для изображения Docker. Как я могу сделать это в командной строке? Я стараюсь избегать загрузки всего и удаления ненужных изображений.
В официальном выпуске Ubuntu, https://registry.hub.docker.com/_/ubuntu/, есть несколько тегов (релиз для него), тогда как при поиске в командной строке
[email protected]:~$ docker search ubuntu | grep ^ubuntu
ubuntu Official Ubuntu base image 354
ubuntu-upstart Upstart is an event-based replacement for ... 7
ubuntufan/ping 0
ubuntu-debootstrap 0
Также с помощью search
в командной строке https://docs.docker.com/engine/reference/commandline/search/, не знаете, как это может работать?
Возможно ли это в команде docker search
?
Если я использую необработанную команду для поиска через API реестра Docker, то информация может быть получена:
$ curl https://registry.hub.docker.com//v1/repositories/ubuntu/tags | python -mjson.tool
[
{
"layer": "ef83896b",
"name": "latest"
},
.....
{
"layer": "463ff6be",
"name": "raring"
},
{
"layer": "195eb90b",
"name": "saucy"
},
{
"layer": "ef83896b",
"name": "trusty"
}
]
Насколько я знаю, CLI не позволяет искать/перечислять теги в репозитории.
Но если вы знаете, какой тег вы хотите, вы можете вывести это явно, добавив двоеточие и имя изображения: docker pull ubuntu:saucy
При использовании CoreOS jq
доступен для анализа данных JSON.
Так же, как вы делали раньше, глядя на library/centos
$ curl -s -S 'https://registry.hub.docker.com/v2/repositories/library/centos/tags/' | jq '."results"[]["name"]' |sort
"6"
"6.7"
"centos5"
"centos5.11"
"centos6"
"centos6.6"
"centos6.7"
"centos7.0.1406"
"centos7.1.1503"
"latest"
Более чистый API v2 доступен уже сейчас, и это то, что я использую в примере. Я docker_remote_tags
простой скрипт docker_remote_tags
:
#!/usr/bin/bash
curl -s -S "https://registry.hub.docker.com/v2/repositories/library/[email protected]/tags/" | jq '."results"[]["name"]' |sort
Включает:
$ ./docker_remote_tags library/centos
"6"
"6.7"
"centos5"
"centos5.11"
"centos6"
"centos6.6"
"centos6.7"
"centos7.0.1406"
"centos7.1.1503"
"latest"
Ссылка:
jq
: https://stedolan.github.io/jq/ | apt-get install jq
Этот скрипт (docker-show-repo-tags.sh) должен работать для любого хоста с поддержкой Docker, у которого есть curl, sed, grep и sort. Это было обновлено, чтобы отразить тот факт, что URL-адреса тегов хранилища изменились.
#!/bin/sh
#
# Simple script that will display Docker repository tags
# using basic tools: curl, sed, grep, and sort.
#
# Usage:
# $ docker-show-repo-tags.sh ubuntu centos
for Repo in $* ; do
curl -sS "https://hub.docker.com/r/library/$Repo/tags/" | \
sed -e $'s/"tags":/\\\n"tags":/g' -e $'s/\]/\\\n\]/g' | \
grep '^"tags"' | \
grep '"library"' | \
sed -e $'s/,/,\\\n/g' -e 's/,//g' -e 's/"//g' | \
grep -v 'library:' | \
sort -fu | \
sed -e "s/^/${Repo}:/"
done
Эта старая версия больше не работает.
#!/bin/sh
# WARNING: This no long works!
# Simple script that will display Docker repository tags.
#
# Usage:
# $ docker-show-repo-tags.sh ubuntu centos
for Repo in $* ; do
curl -s -S "https://registry.hub.docker.com/v2/repositories/library/$Repo/tags/" | \
sed -e $'s/,/,\\\n/g' -e $'s/\[/\\\[\n/g' | \
grep '"name"' | \
awk -F\" '{print $4;}' | \
sort -fu | \
sed -e "s/^/${Repo}:/"
done
Это вывод для простого примера:
$ docker-show-repo-tags.sh centos | cat -n
1 centos:5
2 centos:5.11
3 centos:6
4 centos:6.10
5 centos:6.6
6 centos:6.7
7 centos:6.8
8 centos:6.9
9 centos:7.0.1406
10 centos:7.1.1503
11 centos:7.2.1511
12 centos:7.3.1611
13 centos:7.4.1708
14 centos:7.5.1804
15 centos:centos5
16 centos:centos5.11
17 centos:centos6
18 centos:centos6.10
19 centos:centos6.6
20 centos:centos6.7
21 centos:centos6.8
22 centos:centos6.9
23 centos:centos7
24 centos:centos7.0.1406
25 centos:centos7.1.1503
26 centos:centos7.2.1511
27 centos:centos7.3.1611
28 centos:centos7.4.1708
29 centos:centos7.5.1804
30 centos:latest
Мне не понравилось ни одно из приведенных выше решений, потому что A) они требовали внешних библиотек, которых у меня не было, и которые я не хотел устанавливать. Б) Я не получил все страницы.
Docker API ограничивает вас до 100 элементов на запрос. Это зациклит каждый "следующий" элемент и получит их все (для Python 7 страниц; другие могут быть более или менее… зависимыми)
Если вы действительно хотите спамить сами, удалите | cut -d '-' -f 1
| cut -d '-' -f 1
из последней строки, и вы увидите абсолютно все.
url=https://registry.hub.docker.com/v2/repositories/library/redis/tags/?page_size=100 '# Initial url' ; \
( \
while [ ! -z $url ]; do '# Keep looping until the variable url is empty' \
>&2 echo -n "." '# Every iteration of the loop prints out a single dot to show progress as it got through all the pages (this is inline dot)' ; \
content=$(curl -s $url | python -c 'import sys, json; data = json.load(sys.stdin); print(data.get("next", "") or ""); print("\n".join([x["name"] for x in data["results"]]))') '# Curl the URL and pipe the output to Python. Python will parse the JSON and print the very first line as the next URL (it will leave it blank if there are no more pages) then continue to loop over the results extracting only the name; all will be stored in a variable called content' ; \
url=$(echo "$content" | head -n 1) '# Let get the first line of content which contains the next URL for the loop to continue' ; \
echo "$content" | tail -n +2 '# Print the content without the first line (yes +2 is counter intuitive)' ; \
done; \
>&2 echo '# Finally break the line of dots' ; \
) | cut -d '-' -f 1 | sort --version-sort | uniq;
Образец вывода:
$ url=https://registry.hub.docker.com/v2/repositories/library/redis/tags/?page_size=100 '#initial url' ; \
> ( \
> while [ ! -z $url ]; do '#Keep looping until the variable url is empty' \
> >&2 echo -n "." '#Every iteration of the loop prints out a single dot to show progress as it got through all the pages (this is inline dot)' ; \
> content=$(curl -s $url | python -c 'import sys, json; data = json.load(sys.stdin); print(data.get("next", "") or ""); print("\n".join([x["name"] for x in data["results"]]))') '# Curl the URL and pipe the JSON to Python. Python will parse the JSON and print the very first line as the next URL (it will leave it blank if there are no more pages) then continue to loop over the results extracting only the name; all will be store in a variable called content' ; \
> url=$(echo "$content" | head -n 1) '#Let get the first line of content which contains the next URL for the loop to continue' ; \
> echo "$content" | tail -n +2 '#Print the content with out the first line (yes +2 is counter intuitive)' ; \
> done; \
> >&2 echo '#Finally break the line of dots' ; \
> ) | cut -d '-' -f 1 | sort --version-sort | uniq;
...
2
2.6
2.6.17
2.8
2.8.6
2.8.7
2.8.8
2.8.9
2.8.10
2.8.11
2.8.12
2.8.13
2.8.14
2.8.15
2.8.16
2.8.17
2.8.18
2.8.19
2.8.20
2.8.21
2.8.22
2.8.23
3
3.0
3.0.0
3.0.1
3.0.2
3.0.3
3.0.4
3.0.5
3.0.6
3.0.7
3.0.504
3.2
3.2.0
3.2.1
3.2.2
3.2.3
3.2.4
3.2.5
3.2.6
3.2.7
3.2.8
3.2.9
3.2.10
3.2.11
3.2.100
4
4.0
4.0.0
4.0.1
4.0.2
4.0.4
4.0.5
4.0.6
4.0.7
4.0.8
32bit
alpine
latest
nanoserver
windowsservercore
Если вы хотите версию bash_profile
:
function docker-tags () {
name=$1
# Initial URL
url=https://registry.hub.docker.com/v2/repositories/library/$name/tags/?page_size=100
(
# Keep looping until the variable URL is empty
while [ ! -z $url ]; do
# Every iteration of the loop prints out a single dot to show progress as it got through all the pages (this is inline dot)
>&2 echo -n "."
# Curl the URL and pipe the output to Python. Python will parse the JSON and print the very first line as the next URL (it will leave it blank if there are no more pages)
# then continue to loop over the results extracting only the name; all will be stored in a variable called content
content=$(curl -s $url | python -c 'import sys, json; data = json.load(sys.stdin); print(data.get("next", "") or ""); print("\n".join([x["name"] for x in data["results"]]))')
# Let get the first line of content which contains the next URL for the loop to continue
url=$(echo "$content" | head -n 1)
# Print the content without the first line (yes +2 is counter intuitive)
echo "$content" | tail -n +2
done;
# Finally break the line of dots
>&2 echo
) | cut -d '-' -f 1 | sort --version-sort | uniq;
}
И просто назовите это: docker-tags redis
Образец вывода:
$ docker-tags redis
...
2
2.6
2.6.17
2.8
--trunc----
32bit
alpine
latest
nanoserver
windowsservercore
Я написал инструмент командной строки, чтобы упростить поиск тегов репозитория DockerHub, доступных в моем PyTools GitHub repo. Он прост в использовании с различными ключами командной строки, но в основном:
./dockerhub_show_tags.py repo1 repo2
Он даже доступен как изображение докеры и может принимать несколько репозиций:
docker run harisekhon/pytools dockerhub_show_tags.py centos ubuntu
DockerHub
repo: centos
tags: 5.11
6.6
6.7
7.0.1406
7.1.1503
centos5.11
centos6.6
centos6.7
centos7.0.1406
centos7.1.1503
repo: ubuntu
tags: latest
14.04
15.10
16.04
trusty
trusty-20160503.1
wily
wily-20160503
xenial
xenial-20160503
Если вы хотите встроить в скрипты, используйте -q/--quiet, чтобы получить только теги, например, обычные команды докеров:
./dockerhub_show_tags.py centos -q
5.11
6.6
6.7
7.0.1406
7.1.1503
centos5.11
centos6.6
centos6.7
centos7.0.1406
centos7.1.1503
API v2, похоже, использует какую-то разбивку на страницы, так что он не возвращает все доступные теги. Это хорошо видно в таких проектах, как python
(или library/python
). Даже после быстро прочитав документацию, я не смог правильно работать с API (возможно, это неправильная документация).
Затем я переписал script с помощью API v1 и все еще использовал jq
:
#!/bin/bash
repo="$1"
if [[ "${repo}" != */* ]]; then
repo="library/${repo}"
fi
url="https://registry.hub.docker.com/v1/repositories/${repo}/tags"
curl -s -S "${url}" | jq '.[]["name"]' | sed 's/^"\(.*\)"$/\1/' | sort
Полный script доступен по адресу: https://bitbucket.org/denilsonsa/small_scripts/src/default/docker_remote_tags.sh
Я также написал (в Python) улучшенную версию, которая объединяет теги, указывающие на одну и ту же версию: https://bitbucket.org/denilsonsa/small_scripts/src/default/docker_remote_tags.py
Добавьте эту функцию в ваш файл.zshrc или выполните команду вручную
#usage list-dh-tags <repo>
#example: list-dh-tags node
function list-dh-tags(){
wget -q https://registry.hub.docker.com/v1/repositories/$1/tags -O - | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n' | awk -F: '{print $3}'
}
благодаря этому → Как перечислить все теги для образа Docker в удаленном реестре?
Повторная реализация предыдущего поста с использованием Python вместо sed/awk:
for Repo in $* ; do
tags=$(curl -s -S "https://registry.hub.docker.com/v2/repositories/library/$Repo/tags/")
python - <<EOF
import json
tags = [t['name'] for t in json.loads('''$tags''')['results']]
tags.sort()
for tag in tags:
print "{}:{}".format('$Repo', tag)
EOF
done
Для сценария, который работает с токенами носителя Oauth на Docker-хабе, попробуйте это:
Вывод списка тегов образа Docker на концентратор Docker через HTTP API
Вы можете использовать Visual Studio Code для автозаполнения доступных изображений и тегов докера. Однако для этого необходимо ввести первую букву тега, чтобы увидеть предложения по автозаполнению.
Например, при написании FROM ubuntu
он предлагает варианты автозаполнения, такие как ubuntu
, ubuntu-debootstrap
и ubuntu-upstart
ubuntu-debootstrap
. При написании FROM ubuntu:a
он предлагает варианты автозаполнения, такие как ubuntu:artful
и ubuntu:artful-20170511.1