Share files and directories on the host machine with docker containers

If you used to access files and directories of the host machine from a virtual machine (VM), I believe you have been aware of sharing folders between guest and host in Virtual Box. In the age of cloud and dockerisation, knowing how to share files between the host machine and docker containers is also crucial. In this post, I will show you how to accomplish the same purpose but with Docker containers.

Bind mounts

From Docker documentation, bind mounts provide us with tools to share files on hosts to containers.

Introduction

Bind mounts have been around since the early days of Docker. Bind mounts have limited functionality compared to volumes. When you use a bind mount, a file or directory on the host machine is mounted into a container. The file or directory is referenced by its full or relative path on the host machine. By contrast, when you use a volume, a new directory is created within Docker’s storage directory on the host machine, and Docker manages that directory’s contents.

The file or directory does not need to exist on the Docker host already. It is created on-demand if it does not yet exist. Bind mounts are very performant, but they rely on the host machine’s filesystem having a specific directory structure available. If you are developing new Docker applications, consider using named volumes instead. You can’t use Docker CLI commands to directly manage bind mounts.

 

How to share local files to Docker containers
How to share local files to Docker containers

Choose the -v or –mount flag

Originally, the -v or --volume flag was used for standalone containers and the --mount flag was used for swarm services. However, starting with Docker 17.06, you can also use --mount with standalone containers. In general, --mount is more explicit and verbose. The biggest difference is that the -v syntax combines all the options together in one field, while the --mount syntax separates them. Here is a comparison of the syntax for each flag.

Examples

According to Docker documentation on this topic,  we can use bind mounts to mount a file or directory into a container. Below is an example:

docker run -it --rm \
    --name biomodels \
    --env JUMMP_CONFIG="/mnt/jummp/docker/jummp.properties" \
    -p 8080:8080 \
    -v C:/Users/tnguyen/GoogleOne/tnguyen@ebi.ac.uk/BioModels/Jummp:/mnt/jummp \
    --network my-net
    hub.ebi.ac.uk/biomodels/webapp:1.0-base

References

  1. How to share folders between guest and host in VirtualBox, accessed on 29/05/2020
  2. How can I use a local file on the container?, accessed on 21/05/2020
  3. Use bind mounts, accessed on 30/05/2020

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.