In the first part, we took a look at basics of Docker, building, stopping and removing them. This part will consist of mainly playing with changes and handling the concepts of volumes in docker.

If we have to change few lines of code or “Hello World” to “Hello Div”, we will have to bring down the container, remove it, rebuild the image and then run the container again. But this is too tedious and hence we use a volume to carry out the changes.

Volumes

Volumes is a way for us to create a place in the host machine where we can write files so they are persisted. It’s quite easy to create a volume and we can do so in many different ways, but mainly there are two ways:

  • before you create a container
  • lazily, e.g while creating the container

Creating Volumes:

docker volume create [volume_name]
# To create a name by defining the name
docker volume ls
# To list down all volumes
docker volume prune
# Removes all volumes you are not using
docker volume rm [volume_name]
# Removes a single volume
docker inspect [volume_name]
# Shows more details on the volume

Now we want to use the volume we create in our application. We want to be able to change or create files in our container so that when we pull it down and start it up again our changes will still be there.

# -v, —-volume, the syntax looks like the following: 
-v [name of volume]:[directory in the container]
-v my-volume:/app

# OR

# --mount, the syntax looks like the following
--mount source=[name of volume],target=[directory in container] 
—-mount source=my-volume,target=/app

If we want to start/run the container with the volume we have, we will need to do something like:

docker run -d -p 8000:3000 --name [somename] --volume my-volume:/[volumename] container_name
# Will mount the volume in "/"

# If you create a folder called "logs" and a file called "logs.txt" INSIDE that folder, needing to mount it:
docker run -d -p 8000:3000 --name my-container --volume $(pwd)/logs:/logs divyendrapatil/node                                                           
# The logs folder in the / will contain the logs.txt file
# Which means there is a connection between the volume in the host computer & the container.
# Any changes made on this file will be reflected inside the container.

The entire application as a volume

First kill and remove your first application by:
“docker kill my-container && docker rm my-container”
and run

docker run -d -p 8000:3000 --name my-container --volume $(pwd):/app divyendrapatil/node     

This will make the entire app a directory a volume and any changes made will be reflected inside the container. BUT, if you make any changes on the Node.js Express app, it will not be reflected in the server but rather throw an error. To overcome this issue, we need to install a library like nodemon that will restart the server.