Lab: Docker Secrets
What Are Docker Secrets?
- Docker secrets securely store sensitive information like passwords, API keys, or certificates.
- They allow secure access to secrets in running containers without hardcoding sensitive data into the container or its configuration.
Hands on Lab
-
Change the directory to working directory.
cd /workspaces/ecr_eks_security_masterclass_public/docker-lab
-
Docker Swarm mode must be initialized. Run the following to initialize if not already done.
docker swarm init
-
Create a file with a secret value.
echo "mySuperSecretPassword123" > secret.txt
- This file contains the secret that will be securely stored in Docker.
-
Add this file as a Docker secret.
docker secret create my_secret secret.txt
- Replace
my_secret
with your chosen name for the secret. - You should see a confirmation message showing the secret’s ID.
- Replace
-
List all secrets in your Docker Swarm to verify.
docker secret ls
Note that the secret content is not visible, ensuring secure handling.
- Create a service that uses the secret.
docker service create --name secret_service --secret my_secret alpine sleep 300
This command creates a service called
secret_service
that uses themy_secret
secret.
The container runs
alpine
and sleeps for 300 seconds, giving time to inspect it.
-
Verify the service is running.
docker service ls
-
Get the container ID of the service.
docker ps -q --filter "name=secret_service"
-
Enter the container’s shell.
docker exec -it $(docker ps -q --filter "name=secret_service") cat /run/secrets/my_secret
The secret content should be displayed securely inside the container.
Clanup
-
Remove the service
docker service rm secret_service
-
Remove the secret.
docker secret rm my_secret
-
Delete the temporary secret file from your system:
rm secret.txt