Use bind mounts
In the previous chapter, we talked about and used a volume mount to persist the data in our database. A volume mount is a great choice when you need somewhere persistent to store your application data.
A bind mount is another type of mount, which lets you share a directory from the host’s filesystem into the container. When working on an application, you can use a bind mount to mount source code into the container. The container sees the changes you make to the code immediately, as soon as you save a file. This means that you can run processes in the container that watch for filesystem changes and respond to them.
In this chapter, we’ll see how we can use bind mounts and a tool called nodemon to watch for file changes, and then restart the application automatically. There are equivalent tools in most other languages and frameworks.
Trying out bind mounts
Before looking at how we can use bind mounts for developing our application, let’s run a quick experiment to get a practical understanding of how bind mounts work.
If you’re following these steps on Windows, make sure to use PowerShell and not command prompt (cmd).
1. Open a terminal and make sure your current working directory is in the app directory of the getting started repository.
2. Run the following command to start bash in an ubuntu container with a bind mount.
The mount option tells Docker to create a bind mount, where src is the current working directory on your host machine (getting-started/app), and target is where that directory should appear inside the container (/src).
3. After running the command, Docker starts an interactive bash session in the root directory of the container’s filesystem.
4. Now, change directory in the src directory.
This is the directory that you mounted when starting the container. Listing the contents of this directory displays the same files as in the gettingstarted/app directory on your host machine.
Create a new file named myfile.txt.
Now if you open this directory on the host, you’ll see the myfile.txt file has been created in the directory.
1. From the host, delete the myfile.txt file.
2. In the container, list the contents of the app directory once more. You’ll see that the file is now gone.
3. Stop the interactive container session with Ctrl + D.
And that’s all for a brief introduction to bind mounts. This procedure demonstrated how files are shared between the host and the container, and how changes are immediately reflected on both sides. Now let’s see how we can use bind mounts to develop software.
Contact us +91-9989971070
Register now for Docker and Kubernetes online training
Visit: https://www.visualpath.in/DevOps-docker-kubernetes-training.html