Mounting Volumes
Let’s see how to actually use a volume with a container. We’ll use the official Ghost blogging software image as an example. A blogging software that doesn’t save your posts would be useless, so it’s a perfect use case for volumes!
Running a Container with a Volume
You can mount a volume to a container using the -v flag in your docker run command:
docker pull ghost
# Run Ghost with a volume mounted
docker run -d -e NODE_ENV=development -e url=http://localhost:3001 -p 3001:2368 -v my-vol:/var/lib/ghost ghost
Let’s break down these flags:
-d: Runs the image in detached mode.-e NODE_ENV=development: Sets an environment variable within the container telling Ghost to run in “development” mode.-e url=http://localhost:3001: Sets another environment variable so Ghost knows its access URL.-p 3001:2368: Port forwards the container’s port2368to our host machine’s port3001.-v my-vol:/var/lib/ghost: Mounts themy-volvolume we created to the/var/lib/ghostpath inside the container.
Ghost will now use the /var/lib/ghost directory to persist stateful data (like blog posts) between runs. If you were to navigate to http://localhost:3001/ and create a post, that data would be stored safely in my-vol.