Docker Volumes

Docker Volumes

Used for data persistance for databses and other stateful resource we might use in our app. (when we restart or remove the container our data might get lost). On our local host, our database data is stored in a physical file system, so when we restart container data is lost.

Solution:

On our host we have physical file system, on container we have virtual file system. We connect physical file system path to containers virtual file system path. Now when we make change on host it gets replicated on container when it starts.

Types of volumens:

(using run cmd and mentioning) docker run -v

  1. Host volumes= host file path : container file path
  2. Anonymous volumne= container file path (from host path is automatically fetched by container)
  3. Name volume= name on host: container file path

eg: "docker run -v /home/connect_folder/data:/var/lib/mysql/data"

We can find container default path online which is diff for sql db, mongo db, etc. Best practce is to use name volumes on prod.

Implmenting docker volumes:

  1. If we are using docker run command use "docker run -v" + "volume type"
  2. If we are using docker compose yaml use volumes: "volume type"

NOTE:

Volumes are never deleted unless the parent container is deleted with docker rm -v container_id. If the -v flag is not given, the volume will not be deleted.