This article's content
Docker Volumes

Containers have a "scratch space" that allows you to store files only temporarily, meaning as long as the container is running. But once the container stopped the data is gone.

Volumes are a way to persist information even after a container got destroyed. A volume is a special type of directory in a container (a mount or alias) which maps back to a folder on the host. That can be done in one of two ways: Using named volumes or bind mounts.

Volumes can be shared and reused among containers.

Create a volume that maps to a default folder location on the host

The following command will create a volume that mounts the container's /var/www folder to a default folder location at the host system:

# mount host's default location to container's /var/www 
docker run -p 8080:3000 -v /var/www node

You can docker inspect <container> to look up the paths that are mounted from the host to the container (Listed under "Mounts").

Another way to create a Volume is to give your volume a name like todo-db (named volume):

# create named volume
docker volume create todo-db

# run container using named volume (works even without creating named volume before)
docker run -dp 3000:3000 -v todo-db:/etc/todos getting-started

Create a volume that maps to a folder of your choice on the host system

# run container with volume that has host's current working directory pointing to container's /var/www
docker run -p 8080:3000 -v $(pwd):/var/www node

Remove container including volume

To remove a container including its volume run docker rm -v mycontainer.

Start container with volume and run command in container

To run a command in the docker container you first have to specify a working directory with working directory argument (-w), followed by the image name and the command:

docker run -dp 3000:3000 \
     -w /app -v "$(pwd):/app" \
     node:12-alpine \
     sh -c "yarn install && yarn run dev"

Inspect a volume

docker volume inspect todo-db

About Author

Mathias Bothe To my job profile

I am Mathias, born 40 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 16 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.