- The data doesn’t persist when the container no longer exist, and it can be difficult to get the data out of the container if other process needs it
- A container writable layer is tightly coupled to the host machine where the container is running. You can’t easy move the data somewhere else
Docker containers have stateless services. In case, containers require to run a stateful service like mysql, docker has two options for containers to store files in the host machine.
- Volumes : Managed by docker(/var/lib/docker/volumes)
- Bind Mount : Stored anywhere on host system
Let’s pull a mysql image to understand this concept
docker pull mysql:5.7
Let’s create a container and we know that Mysql is stateful, it stores the data which will keep on changing and we do not make any changes to a container. So we need to fix this issue. So that to fix this problem we required a persistent storage. For that we have an option -v
docker run --name my_db -d -p 3306:3306 -v hostpath:containerpath mysql:5.7
docker run --name my_db -d -e MYSQL_ROOT_PASSWORD=admin123 -p 3306:3306 -v /home/ubuntu/my_db_data:/var/lib/mysql mysql:5.7
where -e stands for exporting the variable to the container. Here we have set the password of the user in the db which is mandatory. Check out the mysql image documentation.
By default mysql stores the data at /var/lib/mysql inside the container and we have created a directory at /home/ubuntu/my_db_data which will store the data available at /var/lib/mysql. Let’s check this.
So the data is saved. We can map this data to new container as well, and if the existing container is lost our data is safe. Let’s do it practically, delete the existing container and create a new container and map the directory data to that.
Docker Volumes
We have a volume concept as well, which is same as above. The only difference is that it stores the data at a specified location. Let’s have a look at it practically
Instead of giving the full path we can simply give the volume name. It is convenient and easy.
Containers are processes running on our host machine
When you install docker engine it creates a virtual interface docker0 which is the gateway IP which act as the switch to all your containers. All the containers created will be connect to docker0 interface.
This docker0 virtual interface would be connected to a real interface eth0 which will throw our requests over the internet whenever needed.