DEV Community

Rhonal Chirinos
Rhonal Chirinos

Posted on

How to Configure Docker Volumes for MySQL

Docker containers are ephemeral by default—this means that any data stored inside a container is lost when the container is stopped or removed. To persist data, Docker provides volumes, which allow you to store and reuse data across container restarts.

Volumes are especially useful for databases like MySQL, where persistent storage is essential. This guide is a quick teaser on how to use Docker volumes to persist MySQL data.

Create a Volume

docker volume create --name storage_test
Enter fullscreen mode Exit fullscreen mode

List All Volumes

docker volume ls
Enter fullscreen mode Exit fullscreen mode

Where Does Docker Store My Volume Data?

docker volume inspect storage_test
Enter fullscreen mode Exit fullscreen mode

💡 This command shows detailed information about the volume, including the path on your host system where the data is stored.

Remove a Volume

docker volume rm storage_test
Enter fullscreen mode Exit fullscreen mode

⚠️ You can’t remove a volume that’s currently in use by a running container.

Run a MySQL Container with a Volume

docker volume create --name storagedb

docker run --name mysql-01 \
  -v storagedb:/var/lib/mysql \
  -e MYSQL_ROOT_PASSWORD=123456 \
  -d mysql:latest
Enter fullscreen mode Exit fullscreen mode

Execute a SQL Script Inside the Container

docker exec -i mysql-01 \
sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' < ./mysql/databases.sql
Enter fullscreen mode Exit fullscreen mode

Notes

💡 Docker volumes are a powerful way to persist and share data across containers. You can also use the same volume in multiple containers if needed.

Thanks for reading! ✨

Top comments (0)