Docker Compose Volume Mounting for Database Persistence¶
Docker Compose volume mounting enables database persistence by mapping a directory on the host machine to a specific directory inside the container.^[600-developer__docker__docker-compose__docker-compouse-02.md] This ensures that data stored by the database survives container restarts, removals, or updates, as the data is physically stored on the host filesystem rather than in the container's volatile writable layer.
Configuration¶
To achieve persistence, the volumes key is used within the docker-compose.yml file to define the mapping between the host path and the container path.^[600-developer__docker__docker-compose__docker-compouse-02.md]
Syntax¶
The general format for defining a volume mount is a string with two paths separated by a colon:
./host-path:/container-path
- Host Path (Left side): The directory on the host machine (e.g.,
./data). Using a relative path refers to a directory relative to the location of thedocker-compose.ymlfile^[600-developer__docker__docker-compose__docker-compouse-02.md]. - Container Path (Right side): The absolute path inside the container where the data is stored or read.
Example: MySQL Persistence¶
In the following example, a MySQL 5.7 service is configured to persist its data directory:
version: "3"
services:
db:
image: mysql:5.7
volumes:
- ./data:/var/lib/mysql
In this configuration:
* ./data represents a folder named data in the same directory as the compose file^[600-developer__docker__docker-compose__docker-compouse-02.md].
* /var/lib/mysql is the default data directory for MySQL inside the container^[600-developer__docker__docker-compose__docker-compouse-02.md].
When the database service runs and writes data, it actually writes to the ./data folder on the host.
Related Concepts¶
- Docker Compose
- [[Docker Volumes]]
- [[Data Persistence]]