automatic docker login within a bash script
To run the docker login command non-interactively, you can set the --password-stdin flag to provide a password through STDIN. Using STDIN prevents the password from ending up in the shell’s history, or log-files.
$ echo $DOCKER_PASS | docker login -u$DOCKER_USER --password-stdin $DOCKER_HOST
When you login to your private registry, docker auto create a file $HOME/.docker/config.json The file had the Credentials info, so you could save the file and copy to any host when you want to login the registry.
The file content like this:
{
"auths": {
"example.com": {
"auth": "xxxxxxxxxxxxxxxxxxxxxxx"
}
}
}
Add-on If you want to login multi docker registry on one server ,just add another auth info.like this:
{
"auths": {
"example.com": {
"auth": "xxxxxxxxxxxxxxxxxxxxxxx"
},
"example1.com":{
"auth": "xxxxxxxxxxxxxxxxxxxxxxx"
}
}
}
Now you can push and pull images from the example.com and example1.com.
Docker 18 and beyond
There's now an officially-documented way to do this:
cat ~/my_password.txt | docker login --username foo --password-stdin
Docker 1.11 through Docker 17
You can pass all the arguments on the command-line:
docker login --username=$DOCKER_USER --password=$DOCKER_PASS $DOCKER_HOST
If you don't specify DOCKER_HOST
, you'll get the main Docker repo. If you leave out any of the arguments, you'll be prompted for that argument.
Older than 1.11
The same path as just above, except that you need to also pass an --email
flag. The contents of this are not actually checked, so anything is fine:
docker login --username=$DOCKER_USER --password=$DOCKER_PASS $DOCKER_HOST --email [email protected]
For any random passer by that may stumble into this looking for a way to use this against an Openshift environment's container registry (Docker) you can use the following to provide the registry URI along with the credentials to log into it using an Openshift token.
$ echo "$(oc whoami -t)" | docker login -u $USER --password-stdin \
$(oc get route docker-registry -n default --no-headers | awk '{print $2}')
Login Succeeded
The above does 3 things:
- Passes token retrieved from Openshift
oc whoami -t
Determines Openshift's registry URI
$(oc get route docker-registry -n default --no-headers | awk '{print $2}'`)
Logs into registry using
$USER
+ token from above