Containers are immutable. We can only re-deploy containers but not change existing ones. This helps in retaining history changes.
Persisting data across containers
There are two options:
- Bind mounts
- Volumes
Bind mount | Volume |
---|---|
When we use a bind mount, a file or directory on the host machine is mounted into a container. This file or directory is referenced by its absolute path on the host machine. | When we use a volume, a new directory is created within Docker's storage directory on the host machine and it's contents are completely managed by Docker. |
Volumes need manual deletion. They can't be cleaned up just by removing a container |
Prune
To cleanup unused volumes:
docker volume prune
List all volumes
docker volume ls
Create a named volume
We can have a named volume with the -v
flag.
docker container run -d --name mysql-container -e MYSQL_ALLOW_EMPTY_PASSWORD=True -v <volume_name>:/var/lib/mysql mysql
The -v
command allows us to do the following:
- Create a new volume for a container
- Create a named volume
For bind mounts, instead of volume_name
, we specify the absolute path of the file or folder in the host in the above command.
docker container run -d --name mysql-container -e MYSQL_ALLOW_EMPTY_PASSWORD=True -v /<absolute_path_on_host>:/var/lib/mysql mysql
Creating docker volumes manually
We can create docker volumes manually using docker volume create
.
This is required when we want to use custom drivers and labels.
NOTE: We need to do this before docker run
.
Top comments (0)