Docker Volumes
Docker volumes let you save data used by your containers, so it doesn’t disappear when the container stops or is removed. Think of it as a way to keep your important files safe and share them across containers.
Why Use Docker Volumes?
Types of Docker Volumes
Hands-On: Using Docker Volumes with MySQL
Step 1: Get the MySQL Image
Download the MySQL image:
docker pull mysql:latest
Step 2: Create a Volume
Create a named volume to store MySQL’s data:
docker volume create mysql-data
Check if it’s created:
docker volume ls
You should see mysql-data in the list.
Step 3: Start the MySQL Container
Run the MySQL container and use the volume:
docker run -d --name mysql-container -e MYSQL_ROOT_PASSWORD=password -v mysql-data:/var/lib/mysql mysql:latest
What this does:
Check if It’s Running
docker ps
You should see mysql-container in the list.
Step 4: Access MySQL
Enter the MySQL shell:
docker exec -it mysql-container mysql -u root -p
Type the password (password) when asked.
show databases ;
Displays all the databases created.
create database demo ;
Creates a Database "demo".
exit
Exits the interactive terminal.
Step 5: Stop and Remove the Container
Stop the container:
docker stop mysql-container
Remove the container:
docker rm mysql-container
Step 6: Check Data Persistence
Run a new container with the same volume:
docker run -d --name mysql-container -e MYSQL_ROOT_PASSWORD=password -v mysql-data:/var/lib/mysql mysql:latest
The data from the old container will still be there, showing that volumes save your data.