Docker volume mounting for data persistence¶
Docker volume mounting is a technique used to ensure data persists across container lifecycle events by mapping a directory on the host machine to a specific path inside a container^[600-developer__docker__docker-compose__docker-compouse-02.md]. This configuration allows data to survive container restarts, removals, or updates, as the files are stored on the host filesystem rather than within the container's writable layer^[600-developer__docker__docker-compose__docker-compouse-02.md].
Implementation in Docker Compose¶
In a docker-compose.yml file, volume mounting is implemented using the volumes directive within a service definition^[600-developer__docker__docker-compose__docker-compouse-02.md]. The configuration typically follows a host_path:container_path syntax^[600-developer__docker__docker-compose__docker-compouse-02.md].
For example, to ensure data persistence for a [[database]] service like MySQL, the following configuration maps a local directory named data to the /var/lib/mysql directory inside the container^[600-developer__docker__docker-compose__docker-compouse-02.md]:
version: "3"
services:
db:
image: mysql:5.7
ports:
- "33060:3306"
volumes:
- ./data:/var/lib/mysql
restart: always
environment:
- MYSQL_USER=tommy
- MYSQL_PASSWORD=tommy
- MYSQL_DATABASE=dockerDb
- MYSQL_ROOT_PASSWORD=root
In this setup, the ./data directory on the host acts as the persistent storage location. This ensures that the database files remain intact on the host machine even if the MySQL container is destroyed or recreated^[600-developer__docker__docker-compose__docker-compouse-02.md].
Sources¶
600-developer__docker__docker-compose__docker-compouse-02.md