You have multiple ways to enable data persistence with docker
In this light tutorial we will cover the two most used possibilities.
-
Data persistence with a folder linked between the host and the container
-
Data persistence with the cmd
docker volume
Install Docker (on debian distro)
Start and test a container
We will take a webserver as an exemple.
docker run -dit --name my-apache-test -p 8081:80 httpd:2.4
Note
|
make sure that port 8081 is available on your host |
You will see your web server welcome page if you connect to your-ip:8081
Now let’s try to modify data inside the container
docker exec -ti my-apache-test bash
Note
|
we use docker exec -ti with cmd bash to enter the container file system
|
We install nano on the container with nano
to test modifying index.html
cd /usr/local/apache2/htdocs apt update && apt install nano nano index.html
We can see that if we restart the container our modifications are still here. However, now if I delete my container, I will lose my data :
docker stop my-apache-test docker rm my-apache-test
If we run our container again with the above cmd docker run -dit --name my-apache-test -p 8081:80 httpd:2.4
we will see a fresh new container without our modified datas.
How to make data persitant
1 - With -v
argument and path to persistent folder
docker run -dit -p 8081:80 -v /home/art/docker-test/html:/usr/local/apache2/htdocs --name my-apache-test httpd:2.4
From my host machine or from my container console, I can now add persistent content to html folder
cd /home/art/docker-test/html echo 'Hello world!' > index.html
docker exec -ti my-apache-test bash cd /usr/local/apache2/htdocs echo '<br>Test from the container' >> index.html
2 - With docker volume
You can use docker volume
to create and administrate docker volumes
docker volume create myvolume
If you want to know where your volume is stored (and other informations)
docker volume inspect myvolume
Let’s launch a web container with this volume mounted
docker run -dit --name httpd-container -p 8081:80 --mount source=myvolume,target=/usr/local/apache2/htdocs httpd:2.4
To edit the data inside the container we need to inside it or edit the volume from the host machine.
Let’s edit from the host machine (more specific)
To know where our volume is stored :
docker volume inspect myvolume sudo su cd /var/lib/docker/volumes/myvolume/_data nano index.html
Note
|
To edit from the host you need now to be root (it’s not common to do so by the way - we do it for testing purpose) |
Now we can launch any container with this volume mounted
docker run -dit --name nginx-container -p 8082:80 --mount source=myvolume,target=/usr/share/nginx/html nginx:stable
Note
|
If you go to your-ip:8082 you will find your same index.html but this time served by nginx 🔥🔥🔥 |