Share data between two running containers by various means depending on the use case. The most common and effective ways include Docker volumes, bind mounts, and inter-container communication through a shared network. Here's how each one works and when it is most applicable:
Using Volumes
Docker volumes are the suggested approach to persisting data as well as sharing data among containers because volumes are controlled by Docker, hence it's portable and secure among environments.
Create a named volume: You can have both containers share a named volume.
Mount the volume in both containers: You have to mount the volume at appropriate path in each of the containers when running them.
Access Data in Both Containers: Any data written to /data in one container will be available to the other, because both containers are using the shared_data volume.
This is useful if you need to share data files, databases, or configuration files between containers. Volumes are also persistent beyond container lifecycle, meaning that data won't be lost when containers are restarted.
Using Bind Mounts
Bind mounts allow you to map a directory on the host machine to a directory in each container, so you can share data with a shared host directory between containers.
Setup shared host directory Create a new shared space on your host, /shared_folder.
Mount the Shared Host Directory in both containers: Now run your two containers, each bound mount pointing to /shared_folder.
Access the data in both containers: Both the containers can access the /data written to it through the host directory.
This kind of mounts is useful while we need the data being written to a container needs to be accessible to some other containers and also needed to be accessible on the host for doing some back-up or any host level operation.
Shared Network and Inter-Container Communication
In situations where containers must share data in real-time using network requests such as through a REST API or TCP connections, one can use a Docker network
Create a Docker Network: In this step, you could create a custom bridge network.
Connect Containers to the Network: Start or join each container to this network.
Share Data using Networking Protocols: Containers can communicate with each other by referencing the container name as a hostname. For instance, if there is a container called container1, it can reach a container called container2 over a protocol like http://container2:port.
- It is useful for microservices or applications that have some need to communicate in real-time but do not want to share data using a file-based mechanism.
- Shared mounts enable sharing between the host and containers so that a shared host directory exists.
- Shared networks allow information to be shared in a real-time basis through the use of network calls. There is also an application for when you have services that run inside multiple containers and no file data has to be accessed between these containers.