DEV Community

Manoj Kumar Patra
Manoj Kumar Patra

Posted on

Docker Cheat Sheet - Container Lifetime and Persistent Data

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:

  1. Bind mounts
  2. 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
Enter fullscreen mode Exit fullscreen mode

List all volumes

docker volume ls
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The -v command allows us to do the following:

  1. Create a new volume for a container
  2. 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
Enter fullscreen mode Exit fullscreen mode

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)