Secrets are used by services that run in the swarm. Usually, secrets are assigned to a service at creation time. Thus, if we want to run a service called web and assign it a secret, api-secret-key, the syntax would look like the following command:
$ docker service create --name web \
--secret api-secret-key \
--publish 8000:8000 \
fundamentalsofdocker/whoami:latest
This command creates a service called web based on the image fundamentalsofdocker/whoami:latest, publishes the container port 8000 to port 8000 on all swarm nodes, and assigns it the secret, api-secret-key.
This will only work if the secret called api-secret-key is defined in the swarm, otherwise an error will be generated with the text secret not found: api-secret-key. Thus, let's create this secret now:
$ echo "my secret key" | docker secret create api-secret-key -
And now, if we rerun the service create command, it will succeed:
We can now do a docker service ps web to find out on which node the sole service instance has been deployed, and then exec into this container. In my case, the instance has been deployed to node-3, thus I SSH into that node:
$ docker-machine ssh node-3
And then I list all my containers on that node to find the one instance belonging to my service and copy its container ID. We can then run the following command to make sure that the secret is indeed available inside the container under the expected filename containing the secret value in clear text:
$ docker exec -it <container ID> cat /run/secrets/api-secret-key
Once again, in my case, this looks like this:
If, for some reason, the default location where Docker mounts the secrets inside the container is not acceptable to you, you can define a custom location. In the following command, we mount the secret to /app/my-secrets:
$ docker service create --name web \
--name web \
-p 8000:8000 \
--secret source=api-secret-key,target=/run/my-secrets/api-secret-key \
fundamentalsofdocker/whoami:latest
In this command, we are using the extended syntax to define a secret which includes the destination folder.