Docker volume mounting patterns¶
Docker volume mounting is the mechanism used to persist and share data between the host machine and containers. A key pattern in volume mounting is the separation of application code from data directories^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md].
Code vs. Data Mounting¶
When building container images, it is standard practice to copy the application source code into the image (e.g., into /app).^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Mounting a volume to the root application directory (e.g., /app) is generally an anti-pattern for production containers. If you bind-mount a host directory to the same location where your application code resides, the mounted files will overwrite or obscure the application files inside the container.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Recommended Data Directory Pattern¶
To prevent overwriting application files, persistent data—such as configuration files, JSON databases, or secrets—should be mounted to a dedicated directory distinct from the application code.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
For example, instead of storing data alongside the script, the data path can be defined as a global variable (e.g., /data/customers.json).^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md] This allows the container to run with the code safely stored in the image while the data is injected from the host.
Example¶
Incorrect (Obscures Code):
# Mounting PWD to /app hides app.py
docker run -v ${PWD}:/app my-app
Correct (Separation of Concerns):
# Mounting PWD to /data preserves app.py in /app
docker run -v ${PWD}:/data my-app
Related Concepts¶
- [[Docker]]
- [[Containerization]]
- [[Flask]]
- [[Persistence]]
Sources¶
^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]