How can I tell if I'm logged in to a private Docker registry from a script?

if docker login worked, you will find a .docker folder on your home directory (~/.docker/), with a config.json file with credentials in it.

otherwise you would get an error login in.

Note: docker determine what credentials to use by looking at the registry name:

if you do

docker pull myregistry.com/myimage:tag

docker will look if you're logged in, and if not will check if you have the credentials for the registry myregistry.com and login with those.

If not you will get a permission error


This is a bit hacky, but it works in most of the cases for me:

if ! grep -q "my.private.registry.com" ~/.docker/config.json ; then
    docker login "my.private.registry.com"
fi

Basically, you search if there is a record of "my.private.registry.com" in ~/.docker/config.json. However, if the session is expired, this check won't catch it.


I believe the error message will vary by registry implementation. However, my own technique is to pull an image that doesn't exist and parse any error message:

$!/bin/sh
repo="$1"
msg=$(docker pull ${repo}/missing:missing 2>&1)
case "$msg" in
  *"requested access to the resource is denied"*|*"pull access denied"*)
    echo "Logged out";;
  *"manifest unknown"*|*"not found"*)
    echo "Logged in, or read access for anonymous allowed";;
  *"Pulling from"*)
    echo "Missing image was not so missing after all?";;
  *) 
    echo "Unknown message: $msg";;
esac

This has been tested with the docker standalone registry and docker_auth. You'll want to test with registries that you may encounter.

If your registry server allows anonymous pulls and you want to verify a push is possible, you can create a dummy empty image and replace the pull with a push of that image. E.g.

#!/bin/sh
repo=$1
# note, I do not like the "." here, better to change it to an empty directory
# see "mktemp" for an option if you cannot make your own empty directory somewhere
docker build -t "${repo}/empty:test" -f - . <<EODF
FROM scratch
EODF
msg=$(docker push "${repo}/empty:test" 2>&1)
rc=$?
if [ "$rc" = "0" ]; then
  echo "Access granted to push"
else
  case "$msg" in
    *"requested access to the resource is denied"*)
      echo "Access denied";;
    *) 
      echo "Unknown error message: $msg";;
  esac
fi