How to use volumes to share data between Docker containers

Edouard Courty
2 min readNov 5, 2022

--

Docker changed the way developers interact and develop software.

No need to install a sh*t load of packages on your machine anymore! Deploying your multi-services app is now a simple and fast task for any developer out there, each of them interacting together if needed!

Let’s now see how data can be shared between two (or more) Docker containers.

A small schema of Docker containers interacting with a volume

Docker containers can interact with data in two ways:

  • It can be copied from the host system to the container using a COPY/ADD command during the build stage
  • Using volumes

A volume is basically a shared folder. You can mount this volume to a path into any container in your stack to share this data between the different containers.

Let’s have an example.

You’re building a simple Node.JS app, and you need to process some files that are generated by another container in your stack.

Here is what your Docker Compose file would look like:

The node service mounts the shared-data volume into the /shared folder, and the file-generator mounts it to /home/app/shared.

This means that any file created from the file-generator service in the /home/app/shared folder will be available from the /shared folder in the node container.

Here is a small demonstration where I create a file from a container and output its content from the other one.

Creating a file from container 1 and reading it from container 2

That’s all you need to know to be able to share data between your Docker containers!

If you liked this Story, make sure to check out my other posts.

I mainly write about programming and tech. Feel free to follow me to support me!

Have a good day :)

--

--

Edouard Courty

Web Developer & IT Teacher based in Paris - Back-end guru - Co-founder of @IMXrarity