Sunday, April 23, 2017

Docker Volumes - How to keep data persistent

Here we are going to see how we can tell a docker image to use a host directory to store that data it may generate.

The reason for this is that images once they are stopped the data it creates is lost, and we really do not want this to happen; specially if we are dealing with a data repository such as cassandra.

Lets consider we a have a cassandra image running like was explained in my previous post Set up Cassandra Cluster with Docker

First of all we are going to stop and remove the image (if was already created).

Lets create a directory in the host system wherever you prefer.

mkdir ~/cassandradata

And now lets start Cassandra image making it to keep its data in the directory just created

docker run -d --name cassandra1 --net=host -v ~/cassandradata:/var/lib/cassandra

We have telled our image to store its data in our directory.

Lets go inside Cassandra image and create a simpole table to see how data is keept.


docker exec -ti cassandra1 cqlsh localhost

Now we create a keyspace and a table.

CREATE KEYSPACE mykeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };

CREATE TABLE mytable (id int PRIMARY KEY, name text, surname text);

INSERT INTO mytable (id,name,surname) values (1,'rafa','reyes');

And lets exit from Cassandra. If we check our directory we can see now something inside it.







We stop our Cassandra image

docker cassandra1 stop

And start it again

docker start cassandra1

If go to our keyspace again and select the data we can see it is still there










So like this we can keep our data safe even if our image stops. Also useful in case you need to move your image to another host system.

No comments:

Post a Comment