Docker Volumes

  • Definition: Docker volumes are used to persist data generated by and used by Docker containers. Volumes are stored on the host filesystem and are independent of the container’s lifecycle.
  • Usage: Volumes allow data to be shared between containers and the host system, making data persistent across container restarts and updates.
  • Lifecycle: Volumes are created using the docker volume create command or automatically when specified in a Docker Compose file. They can be managed (listed, removed) using Docker CLI commands.

Volumes have 2 different uses:

  • Code Synchronisation (Development):
    • During development, it’s common to mount your project directory to the container to reflect code changes immediately without rebuilding the container.
    • This allows you to edit your code on your host machine and see changes instantly within the container, which is useful for rapid development and debugging.
  • Persistence:
    • If your backend service writes data to the filesystem that needs to persist across container restarts, using volumes ensures this data is not lost when the container is stopped or recreated.

How to configure volumes

We can configure containers using docker-compose

Example

services:
	service-1:
		volumes:
			- ./path/on/host:./path/on/container

When the container makes a change in the files in the directory, there will be a corresponding change on the linked path on the host machine

Comparison

FeatureDocker ImagesDocker VolumesDocker Containers
PurposeBlueprint for containersPersistent storage for container dataRunning instances of images
MutableNo (immutable once created)Yes (data can be changed)Yes (state changes during runtime)
CreationBuilt from DockerfilesCreated via Docker CLI or Docker ComposeCreated from Docker images
StorageStored in image registries (e.g., Docker Hub)Stored on host filesystemExist in memory and disk as long as running
IsolationProvides consistent environmentShares data across containers and hostIsolated environment for application
UsageBasis for creating containersPersistent data storageRun applications in isolated environments

Summary

  • Docker Images are the templates used to create containers.
  • Docker Volumes provide persistent storage that can be shared between containers and the host.
  • Docker Containers are the running instances of Docker images that execute applications in isolated environments.