检查docker集线器上是否已经存在image:tag组合

作为bash脚本的一部分,我想检查docker hub上是否存在特别的docker image:tag组合。 此外,它将是一个私人存储库。

即伪代码将如下所示:

tag = something if image:tag already exists on docker hub: Do nothing else Build and push docker image with that tag 

请试试这个

 function docker_tag_exists() { curl --silent -f -lSL https://index.docker.io/v1/repositories/$1/tags/$2 > /dev/null } if docker_tag_exists library/nginx 1.7.5; then echo exist else echo not exists fi 

更新:

如果使用Docker Registry v2(基于此 ):

 # set username and password UNAME="user" UPASS="password" function docker_tag_exists() { 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) EXISTS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/$1/tags/?page_size=10000 | jq -r "[.results | .[] | .name == \"$2\"] | any") test $EXISTS = true } if docker_tag_exists library/nginx 1.7.5; then echo exist else echo not exists fi 

这是一个Bash函数,可以帮助:

 docker_image_exists() { local image_full_name="$1"; shift local wait_time="${1:-5}" local search_term='Pulling|is up to date|not found' local result="$((timeout --preserve-status "$wait_time" docker 2>&1 pull "$image_full_name" &) | grep -v 'Pulling repository' | egrep -o "$search_term")" test "$result" || { echo "Timed out too soon. Try using a wait_time greater than $wait_time..."; return 1 ;} echo $result | grep -vq 'not found' } 

用法示例:

 docker_image_exists elifarley/docker-dev-env:alpine-sshd && \ echo EXISTS || \ echo "Image does not exist" 

我正在努力争取这个工作的私人docker中心存储库,并最终决定写一个ruby脚本,而今天运作。 随意使用!

 #!/usr/bin/env ruby require 'base64' require 'net/http' require 'uri' def docker_tag_exists? repo, tag auth_string = Base64.strict_encode64 "#{ENV['DOCKER_USER']}:#{ENV['DOCKER_PASSWORD']}" uri = URI.parse("https://registry.hub.docker.com/v1/repositories/#{repo}/tags/#{tag}") request = Net::HTTP::Get.new(uri) request['Authorization'] = "Basic #{auth_string}" request['Accept'] = 'application/json' request['Content-Type'] = 'application/json' response = Net::HTTP.start(request.uri.hostname, request.uri.port, use_ssl: true) do |http| http.request(request) end (response.body == 'Tag not found') ? 0 : 1 end exit docker_tag_exists? ARGV[0], ARGV[1] 

注意:你需要指定DOCKER_USER和DOCKER_PASSWORD时调用这个像…

DOCKER_USER=XXX DOCKER_PASSWORD=XXX config/docker/docker_hub.rb "NAMESPACE/REPO" "TAG" && echo 'latest'

如果authentication成功并且指定的标签不存在,这行将打印出“最新”的! 当我尝试抓取基于当前git分支的标记时,我在我的Vagrantfile中使用了这个:

git rev-parse --symbolic-full-name --abbrev-ref HEAD