Module 8 Lesson 3: Hot Reloading with Bind Mounts
Stop rebuilding images. Learn how to use Bind Mounts to link your host source code to your container, enabling 'Instant Feedback' as you type.
Module 8 Lesson 3: Hot Reloading with Bind Mounts
The biggest complaint about Docker in development is: "I have to run docker build every time I change a line of code!"
The solution is Bind Mounts.
1. How Bind Mounts Work
Instead of "Copying" files INTO the image during the build, we "Link" a folder on our laptop directly to a folder inside the running container.
- If you edit a file in VS Code on your laptop, the file inside the container changes instantly.
- Combined with a "Watcher" tool (like
nodemonfor Node.js,flask --debugfor Python, orAirfor Go), the app will restart itself inside the container the moment it sees the file change.
2. Setting it up in Docker Compose
services:
web:
build: .
volumes:
- .:/app # Link the current folder to /app inside the container
command: nodemon app.js # Use a watcher instead of 'node app.js'
The "Node Modules" Problem
A common mistake is syncing your local node_modules into the container. This can break things because the libraries might be compiled for Mac, but the container is running Linux.
The Fix (Anonymizing the Volume):
volumes:
- .:/app
- /app/node_modules # This "Hides" the container's node_modules from your host
3. Performance Tips for Mac and Windows
Syncing thousands of files (like in a React project) can be slow on Mac/Windows because they use a virtual machine to run Docker.
- Use
delegated:- .:/app:delegated(Tells Docker that the host's view of the file is more authoritative, making it faster). - Docker Desktop "VirtioFS": Ensure this is enabled in your settings for the fastest file syncing.
4. When to Use Bind Mounts vs. COPY
| Situaton | Use... | Why? |
|---|---|---|
| Local Development | Bind Mount | You want instant changes without rebuilds |
| Testing / CI | COPY | You want a self-contained image that doesn't rely on the host |
| Production | COPY | Maximum security and reliability |
Exercise: The Live Refresh
- Create a folder with a simple
index.htmlfile. - Run an
nginxcontainer and mount your current folder to Nginx’s web directory.- Hint:
docker run -p 8080:80 -v $(pwd):/usr/share/nginx/html nginx
- Hint:
- Visit
localhost:8080in your browser. - Change the text in your
index.htmland save it. - Refresh your browser. Did the text change? (If yes, you just performed your first hot-reload!).
- Why is this better than having to
docker stop,docker build, anddocker runfor every typo?
Summary
Bind mounts are the bridge between your "Code Editor" and your "Runtime Environment." By combining them with a file-watcher, you get the best of both worlds: the consistency of Docker and the speed of local development.
Next Lesson: Finding the bugs: Debugging applications in containers.