With Data volumes sharing of data is possible between a Docker container and a host system.
As part of our Server Support Services here at Ibmi Media, we have helped our customers perform Docker tasks on a regular basics.
In this context, we shall take you through the steps to perform these task.
Data contained in a Docker container is only accessible within the container by default and only available when the container is running.
As earlier stated, the sharing of data and files between a host system and the Docker container is possible by means of the Docker volumes.
As you read on, you will learn how to make the data inside of the container accessible on the host machine from outside of the container.
To begin, create a directory for the volume. Open your terminal window and enter the command below;
mkdir ~/container–data
Next, mount a volume into this directory. To make it more clearer to you, we will consider an instance whereby a container is being deployed on Ubuntu. With a directory called "data" already created and a host directory "~/container-data", the command to deploy a volume into this directory will look like this;
docker run –dit –P —name ubuntu–test –v ~/container–data:/data Ubuntu
After the process is completed, a container ID will be assigned. To get this ID, simply run the command below;
docker ps -a
Let us check the recently deployed container. Use the command below;
docker attach ID
Here "ID" is usually the first four characters of the deployed container. You can list the current directory with the command below;
ls /
The will show you if the /data directory is available in the Ubuntu container. Next create a test file in that directory using the command below;
touch /data/test
Now list the contents in that directory with the command below;
ls ~/container-data
You will see the test file there.
To create a database volume, first deploy a MySQL database Docker container with a storage volume named "mysql-data-volume". Use the command below;
docker run —name mysql–test –v mysql-data-volume:/var/lib/mysql –e MYSQL_ROOT_PASSWORD=passwd –d mysql:latest
Here "e" switch tells docker that it is associated with an environment variable.
Check the contents of the container via the bash prompt using the command below;
docker exec –it ID /bin/bash
Then list the contents of this container located at the mysql directory "/var/lib/mysql" using the command below;
ls /var/lib/mysql
Now you can exit the container with the command;
exit
Check the contents of the mounted volume of the host with the command below;
sudo ls /var/lib/docker/volumes/mysql-data-volume/_data
The complete guide on how to setup Docker volumes and how to share data between a Docker container and a host system.