Tuesday, January 11, 2022

Attaching Persistent storage to a container

How to attach Persistent storage to a container


    As we all know containers are ephemeral in nature and it does not persist the data. If container is removed the data is gone along  with it. So per fix this issue, we can attached a persistent storage with container. To do the same, we configure a folder on host file system to be attached to container for persistent storage.

we will start will creating a folder on host system.




We will also need to take care of SElinux labeling, so we will setup a rule for '/var/local/mysql' folder and anything underneath. So once rule is set run restorecon to change label.







After the selinux labeling is setup we will also have to take care of file system permission, so that container to write on the filesystem of host. Since we are taking example of Mysql process, we will change ownership to mysql uid and gid for the folder.





Now we are all set to run a container. So we will have to pull the image. You might need to login to the registry if needed. 












Now we have the image fetached, lets run the container with the storage mount of '/var/local/mysql' folder of host to container folder of '/var/lib/mysql/data'.

-d = Running container in background
-v = Bind a volume
-e = Environmental variable









After running the container, you will find bunch of files created underneath the /var/local/mysql folder. Also you might notice that the files are owned by Mysql uid and gid.

















Now, we will access the shell of the container to access the mysql process.











We can access the database we created called 'projectmanhattan' and  we will create the database with a table called 'newyork'.














One table is created under the database, lets populate it with some data to test the data persistence of storage.













Now we will delete the old container named 'mydb1' and create another container named 'mydb2' with same properties and mounting the same volume to verify if data persisted or not. We can see that data still exists even after deleting the initial container.
 
















Conclusion: 

We are able to persist the data if we mount the host file system storage in the container.

Hope that helps.