Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #28: Named Volumes vs Path Based Volumes

blog/cards/docker-tips-and-tricks.jpg

There's a couple of ways to save and sync data between a container and your Docker host. Let's compare 2 of them.

Named volumes look like this postgres:/var/lib/postgresql/data. If you’re using Docker Compose, it will automatically create the volume for you when you first do a docker-compose up, but if not you would need to create it yourself by running docker volume create postgres.

The name doesn’t need to be postgres, but it’s a best practice to name your volumes so you know what they refer to later. You can prefix them with your project’s name to avoid name conflicts.

When you use a volume like this, Docker will manage the volume for you. On Linux, that volume will get saved to /var/lib/docker/volumes/postgres/_data. If you’re running Windows or MacOS it will get saved somewhere else, but the moral of the story is, you don’t need to worry about it. You can set it and forget it, and it will work across all systems.

Path based volumes serve the same purpose as named volumes, except you’re responsible for managing where the volume gets saved on the Docker host. For example if you did ./postgres:/var/lib/postgresql/data then a postgres/ directory would get created in the current directory on the Docker host.

If you go this route you’ll notice that the permissions will be the same as what they are set to in your Dockerfile or what you set with the --user flag when running the container. If you did none of that then the contents of that folder will be owned by root.

Which One Should You Use?

Back before named volumes existed, it was always a question on where you should store these volumes. Some people put them in a data/ folder relative to your project. Other people put them in ~/.docker-volumes and this quickly got weird because now you’re writing volumes out to areas of your host’s file system that are unrelated to the project.

My rule of thumb is, if you’re dealing with data that you’re not actively dealing with directly then use a named volume and let Docker manage it.

However, if you’re using a volume in development and you want to mount in the current directory so you can code your project without rebuilding then by all means use a path based volume because that’s 100% normal and is considered a best practice. For example, you may see that referenced as .:/app in a docker-compose.yml file.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments