Sharing Data Between Containers
One of the great benefits of Docker volumes is the ability to share data between containers. Let's create another container that uses the same volume:
docker run -d --name another_container -v my_data:/app/shared_data ubuntu:latest sleep infinity
This command is very similar to the one we used before, but we're giving the container a different name and mounting the volume to a different path inside the container.
Now, let's verify that this new container can access the data we created earlier:
docker exec another_container cat /app/shared_data/test.txt
You should see the same "Hello from Docker volume" message we wrote earlier. This shows that both containers are accessing the same data.
Let's add some more data from this new container:
docker exec another_container sh -c "echo 'Data from another container' >> /app/shared_data/test.txt"
This command appends a new line to our test.txt
file.
Now, if we check the contents of the file from either container, we should see both lines:
docker exec my_container cat /app/data/test.txt
You should see both "Hello from Docker volume" and "Data from another container" in the output.
This demonstrates how Docker volumes can be used to share data between containers, which is incredibly useful for many applications.