Use multiple logins for the same Docker registry

Use case

When Docker images are uploaded to our registry they are separated by namespace based on the project they belong to. Each project has two dedicated service accounts - one for CI with pull and push permissions and one for deployments with pull permissions only. By default Docker stores auth tokens by registry (hostname) which means that concurrent access to the same registry with different project specific accounts leads to problems.

Solution 1

You can use the –config option of the Docker client to store multiple credentials into different paths:

echo "${DOCKER_REGISTRY_PASS1}" | docker --config ~/.docker/project1 login ${DOCKER_REGISTRY} --username ${DOCKER_REGISTRY_USER1} --password-stdin
echo "${DOCKER_REGISTRY_PASS2}" | docker --config ~/.docker/project2 login ${DOCKER_REGISTRY} --username ${DOCKER_REGISTRY_USER2} --password-stdin

Then you are able to call Docker commands by selecting your credential:

docker --config ~/.docker/project1 pull registry.example.com/project1/image:latest
docker --config ~/.docker/project2 pull registry.example.com/project2/image:latest

Solution 2

Instead of always having to manually pass the config path to the docker command it’s easier to simply configure it via environment variable:

export DOCKER_CONFIG="${HOME}/.docker/${CI_PROJECT_NAMESPACE}"
echo "${DOCKER_REGISTRY_PASS}" | docker login ${DOCKER_REGISTRY} --username ${DOCKER_REGISTRY_USER} --password-stdin

Sources: