How to Keep Your Data Safe When a Docker Container Crashes

 When using Docker, it’s important to ensure your data isn’t lost if a container crashes or is removed. Normally, containers operate in isolation, and any data inside them is lost when they stop or are destroyed. So, how can we make sure our data persists? The answer is by using Docker Volumes.

What is a Docker Volume?

A Docker Volume allows you to store data outside of the container on your host machine. This way, even if the container is removed, the data remains available and can be used by other containers.

Steps to Persist Data with Docker Volumes

Here’s a step-by-step guide to creating and using a Docker Volume:

  1. List existing Docker Volumes:
  • docker volume ls

This command shows all the volumes currently available.

2. Create a new Docker Volume:

  • docker volume create mysql-data

This creates a volume named mysql-data on your host machine.

3. Inspect the Volume:

  • docker volume inspect mysql-data

This provides detailed information about the volume.

4.Run a MySQL Container with the Volume:

  • docker run -d --name mysql-demo -v mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:5.7

Explanation:

  • --name mysql-demo: Names the container mysql-demo.
  • -v mysql-data:/var/lib/mysql: Maps the mysql-data volume to /var/lib/mysql inside the container. This is where MySQL stores its data.
  • -e MYSQL_ROOT_PASSWORD=root: Sets the MySQL root password to root.

5. Access the MySQL Container:

  • docker exec -it mysql-demo bash

This command opens a bash terminal inside the mysql-demo container.

6. Use MySQL inside the Container:

  • mysql -u root -p

Log in to MySQL using the root user and the password set earlier (root).

7. Create and View a Database:

  • CREATE DATABASE devops; SHOW DATABASES;

This creates a new database named devops and lists all databases.

8. Stop and Remove the Container:

  • docker stop mysql-demo && docker rm mysql-demo

This stops and removes the mysql-demo container.

9. Re-run the Container and Check Data Persistence:

  • docker run -d --name mysql-demo -v mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:5.7
  • docker exec -it mysql-demo bash
  • mysql -u root -p
  • SHOW DATABASES;

Even after removing and re-running the container, the devops database will still exist because the data is stored in the mysql-data volume on the host machine.

Conclusion

By using Docker Volumes, you can ensure that your data is safe and persists even if a container is removed or crashes. Give it a try and see how it simplifies data management in your Docker environment!

Comments

Popular posts from this blog

📘 Understanding Prometheus in a Simple Way-Part 3 (For DevOps Beginners)

Grafana Setup & Dashboard Creation (Part-5)— Explained by Raees Yaqoob Qazi

My First Python Program: A Simple Calculator