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

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

And then remove them using their name:

 
docker volume rm <volume_name>

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

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

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github