How To Deal With Persistent Storage (e.g. Databases) In Docker?

Better Stack Team
Updated on August 1, 2022

The best way to deal with persistent data storage (such as a database) in Docker is to use Docker’s volume API (for docker 1.9.0 or newer) or use data-only containers for older versions of Docker.

Docker 1.9.0 or newer

The best approach for you is to use docker volume API as shown in the following example:

docker volume create --name myvolume
docker run -d -v myvolume:/container/path/for/volume container_image my_command
Copied!

Let’s break down the example command:

  • The first command creates a new volume named myvolume in the current working directory
  • The second command runs the container image container_image and configures it to consume the newly created volume myvolume

If you create a container with a -v volume_name:/container/fs/path Docker will automatically create a named volume for you that can:

  1. Be listed through the docker volume ls
  2. Be identified through the docker volume inspect volume_name
  3. Backed up as a regular directory
  4. Backed up as before through a --volumes-from connection

You can also identify dangling volumes (unused volumes)

docker volume ls -f dangling=true
Copied!

And then remove them using their name:

docker volume rm <volume_name>
Copied!

Docker 1.8.X and older

The approach that seems to work best for production is to use a data-only container. The data-only container is run on a barebones image and does nothing except expose a data volume.

Then you can run any other container to have access to the data container volumes:

docker run --volumes-from data_container some_other_container command_to_exec
Copied!

You can read more about this technique in the official documentation.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack