A Little Bit TechA Little Bit Tech
HOME LAB34 min read

Docker Storage and Persistence: A Beginner-to-Expert Guide

Learn where Docker keeps container data and how to keep it safe: volumes, bind mounts, tmpfs, NAS storage over NFS and SMB, storage drivers, disk usage, and backup strategies you can actually restore.

By Mark Poulton

A container made of read-only image layers and a writable layer that is deleted with the container, with four mount points leading to a named volume managed by Docker, a bind mount to a host path, a tmpfs mount in host memory and an NFS share on a NAS; the volume, bind mount and NFS share feed a backup step, while tmpfs is not backed upA container made of read-only image layers and a writable layer that is deleted with the container, with four mount points leading to a named volume managed by Docker, a bind mount to a host path, a tmpfs mount in host memory and an NFS share on a NAS; the volume, bind mount and NFS share feed a backup step, while tmpfs is not backed up

Docker Storage and Persistence: A Beginner-to-Expert Guide

Containers are disposable. Anything a container writes to its own filesystem is deleted with the container, and Docker deletes and recreates containers every time you update an image or change a Compose file. To keep data, you put it on a mount: a named volume managed by Docker, a bind mount of a host folder, or network storage such as an NFS share on a NAS. Then you back up those mounts, and restore one now and then to prove the backups work.

This guide is the fourth in the A Little Bit Tech Docker series. The weekend project to build a properly managed Docker host sets up a server with a tested backup, the ten best Docker containers for home users suggests what to run, and the Docker Compose beginner-to-expert guide covers the Compose file itself. This article goes deep on storage:

  • Beginner: why container data disappears, volumes versus bind mounts, and which commands actually delete data.
  • Intermediate: pre-populated volumes, read-only mounts, file ownership, tmpfs and the Compose volume options.
  • NAS storage: two ways to mount NFS shares into containers, SMB/CIFS shares, and what shouldn't live on network storage.
  • Advanced: image mounts, storage drivers and the containerd image store, moving Docker's data directory, and controlling disk usage.
  • Backups: what to back up, how to capture it consistently, the 3-2-1 rule, off-site copies and restore tests.

Each section stands on its own, so skip to the level you need. Commands and behaviour were checked against Docker's documentation in November 2026. Version-specific details are called out where they matter.

Why does Docker container data disappear?

Every container is built from an image, which is a stack of read-only layers. When the container starts, Docker adds a thin writable layer on top. Every file the container creates or changes goes into that writable layer.

Docker's documentation is blunt about what happens next: data written to the container layer doesn't persist when the container is destroyed. The writable layer belongs to one container and is deleted with it. The image underneath is unchanged, which is why a recreated container starts out clean.

That's a problem because containers are recreated more often than you might think:

  • docker compose up -d recreates any service whose image or configuration changed.
  • docker compose pull followed by up -d, the normal update routine, recreates every updated service.
  • docker compose down removes the containers outright.

So the rule is simple: any path where an application writes data you want to keep must be a mount. A mount replaces part of the container's filesystem with storage that lives outside the container and outlives it.

There's a performance reason too. Writes to the writable layer go through the storage driver's union filesystem, which adds overhead. Docker's documentation says volumes write directly to the host filesystem and recommends them for write-heavy data. Databases in particular should never write to the container layer.

What are the Docker storage types?

Docker offers five kinds of mount. Most home labs need only the first three.

TypeWhere the data livesSurvives container removalTypical use
Named volumeA directory Docker manages, under /var/lib/docker/volumes on LinuxYesDatabases and application data
Bind mountAny file or folder on the host you chooseYesConfig files you edit, media libraries, sharing files with the host
tmpfs mountHost memory (Linux only)No, gone when it stopsCaches, scratch space, sensitive temporary files
Image mountThe read-only filesystem of another imageNot applicable, read-onlyDebugging tools, shared read-only assets
Named pipeA Windows named pipeNot applicableWindows containers talking to the Docker Engine

Network storage isn't a separate type. An NFS or SMB share reaches a container either as a bind mount of a folder the host has mounted, or as a volume whose driver mounts the share for you. Both approaches are covered in detail below.

Docker storage types: a container made of read-only image layers and a writable layer deleted with the container, with mount points for a named volume, a bind mount, a tmpfs mount and an NFS share on a NAS, and backups covering everything except tmpfs.Docker storage types: a container made of read-only image layers and a writable layer deleted with the container, with mount points for a named volume, a bind mount, a tmpfs mount and an NFS share on a NAS, and backups covering everything except tmpfs.

Named volumes: Docker-managed storage

A named volume is storage that Docker creates and manages. You refer to it by name, and Docker decides where it lives on disk.

docker volume create app-data
docker volume ls
docker volume inspect app-data

inspect shows the Mountpoint, which on a Linux host looks like /var/lib/docker/volumes/app-data/_data. Mount the volume into a container with --mount or -v:

docker run -d --name app \
  --mount type=volume,src=app-data,dst=/data \
  nginx:1.29-alpine

In Compose, declare the volume at the top level and reference it from the service:

services:
  db:
    image: postgres:17-alpine
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

Compose prefixes volume names with the project name, so this volume is called <project>_db_data on the host. That's why setting name: at the top of every Compose file matters: rename the folder without it, and Compose creates a new, empty volume under a new project name.

Docker's documentation lists the reasons to prefer volumes:

  • They're easier to back up and migrate than bind mounts.
  • You manage them with the Docker CLI and API, the same as everything else.
  • They work on Linux and Windows containers, and on Docker Desktop.
  • They can be shared more safely between containers.
  • A new volume can be pre-populated with the image's existing content, as described later.
  • They give the same raw file performance as the host filesystem.

One rule matters more than the rest: don't read or edit files under /var/lib/docker/volumes directly from the host. Docker's documentation calls direct access unsupported, undefined behaviour that can break the volume or its data. Use a container to get at a volume's contents, as shown in the backup section.

Anonymous volumes

If you mount a volume without a name, such as -v /data, Docker creates an anonymous volume with a random ID. Some images also declare a VOLUME in their Dockerfile, which creates an anonymous volume when you don't mount anything at that path.

Anonymous volumes are easy to lose. Each new container gets a fresh one rather than reusing the last one, so data written to an anonymous volume is effectively orphaned the next time the container is recreated. The docker compose down reference warns about exactly this: anonymous volumes aren't removed by default, but "they are not automatically mounted by a subsequent up."

The fix is to always give data a name. Run docker inspect <container> and look at Mounts. Any volume with a 64-character hexadecimal name is anonymous, and it's worth checking whether that path holds data you care about.

Bind mounts: host folders in containers

A bind mount maps a file or folder on the host into the container. The container sees exactly what's on the host, and changes in either place are immediately visible in the other.

services:
  app:
    volumes:
      - ./config:/config          # relative to the folder containing compose.yaml
      - /srv/media:/media:ro      # absolute path, read-only

Relative paths are resolved from the Compose file's folder and should start with . or .., so Compose doesn't mistake them for volume names.

Docker's documentation suggests bind mounts for:

  • Configuration files you want to edit on the host.
  • Sharing source code or build output between the host and a container during development.
  • Files a container generates that you want to use on the host.

Bind mounts have trade-offs:

  • They have write access to the host by default. A process in the container can create, change or delete host files under the mounted path. Mount only the folders an application needs, and add :ro where it only reads.
  • They tie a container to one host's folder layout. Move the Compose file to another server and the paths must exist there too.
  • They're created on the Docker daemon's host, not your client. If you manage a remote Docker host from your laptop, the bind mount path refers to the server's filesystem.

What happens when a bind mount path doesn't exist

This is a classic surprise, and the behaviour depends on the syntax:

SyntaxMissing host path
docker run -v /host/path:/targetDocker creates it, always as a directory
docker run --mount type=bind,src=/host/path,...Error: bind source path does not exist
--mount with bind-create-srcDocker creates it
Compose short syntax ./path:/targetCompose creates it as a directory
Compose long syntax with bind.create_host_path: falseError, the container doesn't start

If a container fails because a config file "is a directory", this is why: the file didn't exist when the container first started, so Docker created a directory in its place. Delete the empty directory, create the file, then recreate the container.

The error behaviour is useful, not just annoying. Later in this article it becomes a safety check that stops a container from writing to the local disk when a NAS share isn't mounted.

Should you use a volume or a bind mount?

Short answer: use named volumes for data that only the application touches, and bind mounts for files you need to see or edit on the host.

DataRecommended mountWhy
Database files (PostgreSQL, MariaDB, Redis)Named volume, local diskDocker-managed, fast, nothing else should touch the files
Application state and uploadsNamed volumeSurvives updates, easy to back up with a container
Config files you edit by handBind mountEdit with your usual tools and keep in Git alongside compose.yaml
Media libraries, photos, downloadsBind mount or NFS volumeLarge, shared with other tools, often lives on a NAS
Caches and scratch spacetmpfs or nothingDisposable by definition
Secrets and certificatesCompose secrets, or a read-only bind mountLeast privilege, covered in the Compose guide

Plenty of experienced self-hosters use bind mounts for everything, because a folder per service under one project directory is easy to understand and back up with ordinary tools. That works, with two cautions. You take on file ownership yourself, which is covered below. And a database's files still can't be copied safely while it's running, whichever mount type holds them.

-v or --mount: which syntax?

docker run accepts two syntaxes for the same mounts. Docker's documentation prefers --mount because it's explicit and supports every option:

# Short form
docker run -v app-data:/data:ro nginx:1.29-alpine

# Long form, same result
docker run --mount type=volume,src=app-data,dst=/data,readonly nginx:1.29-alpine

You must use --mount to pass volume driver options, to mount a subdirectory of a volume, to control recursive read-only behaviour, or to mount an image. Compose has the same split: the short source:target:mode form, and a long form with type, source, target and nested options.

What deletes Docker volumes, and what doesn't?

Most data loss in a home lab comes from a cleanup command that did more than expected. These are the facts from Docker's command references:

CommandRemoves containersRemoves named volumesRemoves anonymous volumes
docker compose downYesNoNo
docker compose down -vYesYes, those declared in the fileYes, those attached to its containers
docker rm <container>YesNoNo
docker rm -v <container>YesNoYes
docker run --rm ...When it exitsNoYes
docker volume rm <name>NoYes, that volumeYes, if named by ID
docker volume pruneNoNoYes, if unused
docker volume prune -aNoYes, every unused oneYes, if unused

Three of these deserve emphasis:

  • down -v deletes your data. Volumes marked external: true are never removed by down, which is one reason to use them for irreplaceable data.
  • "Unused" means "not referenced by any container", not "not running". After docker compose down, a stack's containers are gone, so its volumes count as unused. Running docker volume prune -a at that moment deletes them.
  • docker volume prune has changed. It now removes only anonymous volumes by default. The --all flag, available from API version 1.42, extends it to named volumes. Older guides that show plain prune deleting named volumes describe older behaviour.

docker system prune leaves volumes alone unless you add --volumes. Treat any command with -v, --volumes or -a as one that needs a fresh backup first.

Intermediate: making volumes behave

Pre-populated volumes and nocopy

When you mount an empty volume at a path where the image already has files, Docker copies those files into the volume first. This is how an official image's default configuration ends up in your volume on first start.

Three details matter:

  • It applies to volumes only. A bind mount simply hides whatever the image had at that path.
  • It happens only when the volume is empty. Once it contains anything, Docker leaves it alone, so later image updates don't overwrite your files.
  • You can turn it off with volume-nocopy (--mount) or volume: { nocopy: true } (Compose) when you want the application to initialise the path itself.

Mounting over existing files hides them

A non-empty volume or any bind mount obscures what the image had at the target path. Docker's documentation compares it to mounting a USB drive over /mnt. The original files are still in the image, but there's no way to reveal them without recreating the container without the mount.

This explains a common mistake: mounting a host folder over an application's install directory instead of its data directory. The container then can't find its own program files. Mount the data path the image's documentation names, and nothing broader.

Check the data path for each image: the PostgreSQL 18 change

Mount paths are defined by each image, and they do change. The official PostgreSQL image is the best current example:

  • PostgreSQL 17 and earlier: mount the volume at /var/lib/postgresql/data. The image documentation warns that mounting at /var/lib/postgresql instead "WILL NOT PERSIST database data when the container is re-created."
  • PostgreSQL 18 and later: PGDATA is version-specific (/var/lib/postgresql/18/docker for 18), and the declared volume moved to /var/lib/postgresql. Mount the volume at /var/lib/postgresql.

The change makes major-version upgrades with pg_upgrade --link faster. The catch is that an old Compose file with the 17-style path, combined with an 18 image, writes the database somewhere that isn't your volume. Read the image documentation's storage section before every major version change, and check docker inspect afterwards to confirm the data path is on a mount.

Read-only mounts

Add :ro or read_only: true whenever a container only needs to read:

volumes:
  - ./site:/usr/share/nginx/html:ro
  - type: bind
    source: /srv/media
    target: /media
    read_only: true

Read-only mounts are a cheap security control: a compromised or buggy app can't modify or encrypt what it can't write to. Several containers can share one volume with some mounting it read-write and others read-only.

One subtlety applies to bind mounts that contain other mounts, such as a folder with a NAS share mounted inside it. On Linux kernel 5.12 and later, Docker makes those submounts read-only too, on a best-effort basis. On older kernels, submounts stay writable even when the outer mount is read-only. The --mount option bind-recursive=readonly makes this strict, and errors on older kernels rather than silently leaving them writable.

File ownership and permissions

Linux file permissions use numeric user and group IDs, and those numbers mean the same thing inside and outside the container. If a container process runs as UID 1000, it can write to a bind-mounted folder only if UID 1000 has permission on the host.

Most "permission denied" errors on mounts come from one of these:

  • The container runs as a different user than the folder's owner. Check the container's user with docker exec <container> id, and the folder's owner with ls -ln on the host. Match them with chown, or set the container's user with user: in Compose.
  • The image switches users at startup. Many images expose variables such as PUID and PGID (LinuxServer.io images use these) to choose the runtime user. Set them to your host user's IDs.
  • The folder was auto-created by Docker as root. A missing bind-mount path is created by the daemon, which runs as root. Create folders yourself, with the right owner, before the first start.
  • SELinux is blocking access. On SELinux systems such as Fedora and RHEL, a correct UID isn't enough. See below.

Don't fix permissions with chmod 777. It hides the real problem and lets every user and container on the host modify the files.

SELinux labels

On hosts with SELinux enforcing, a container can't read a bind-mounted folder until the folder has the right security label. Add z or Z to the mount options:

  • z relabels the content so several containers can share it.
  • Z relabels it as private to one container.

Docker's documentation is emphatic about the risk: relabelling changes the host files themselves, and bind-mounting a system directory such as /home or /usr with Z can make the host unusable. Only use these options on folders that exist for the container. The SELinux options can only be set with -v or the Compose syntax, not with --mount.

tmpfs: memory-backed scratch space

A tmpfs mount keeps files in host memory. Nothing is written to disk, and everything is gone when the container stops. It's useful for:

  • Scratch space for containers with a read-only root filesystem, as in the Compose hardening section.
  • Caches you don't want wearing out an SSD or SD card.
  • Short-lived sensitive files you don't want written to disk.
services:
  app:
    read_only: true
    tmpfs:
      - /tmp
    volumes:
      - type: tmpfs
        target: /cache
        tmpfs:
          size: 268435456   # 256 MiB, in bytes

Things to know about tmpfs:

  • It's Linux only, and can't be shared between containers.
  • It counts against the container's memory limit. A large tmpfs size doesn't give the container extra RAM. Filling the mount can cause an out-of-memory kill.
  • The default maximum size is 50% of the host's RAM for --mount type=tmpfs when you don't set one. Set an explicit size.
  • It may still reach disk via swap. Docker's documentation notes that tmpfs data can be written to swap. Don't rely on tmpfs as a guarantee that a secret never touches disk.
  • The default mode is 1777, world-writable with the sticky bit, like /tmp. Set mode if that's too open.

Compose volume options: name, external and labels

The top-level volumes section has a few options worth knowing:

volumes:
  db_data:
    name: wiki-db-data        # exact name, no project prefix
    labels:
      tech.alittlebit.backup: "daily"
  media:
    external: true            # created outside Compose, never deleted by it
    name: nas-media
  • name sets the exact volume name. Use it when other tools, such as backup scripts, need a stable name.
  • external: true tells Compose the volume already exists. Compose won't create it, errors if it's missing, and never removes it with down -v. All other options except name are invalid alongside it.
  • labels add metadata, visible in docker volume inspect. Docker recommends reverse-DNS names. Labels make filters possible, such as pruning only volumes with a particular label.

docker compose up creates any non-external volume that doesn't exist. If someone deletes one by hand, Compose quietly creates a new empty one on the next up. That's convenient for disposable data and dangerous for important data, which is another reason to make irreplaceable volumes external.

Sharing volumes between containers

Several services can mount the same named volume. Two refinements help:

  • Subdirectories. Docker can mount a single subfolder of a volume, with volume-subpath on --mount or volume: { subpath: ... } in Compose. The subfolder must already exist in the volume, or the mount fails.
  • volumes_from. A service can mount every volume of another service, read-write by default or with :ro. It's mostly used for one-off maintenance and backup containers.
services:
  app:
    volumes:
      - type: volume
        source: shared
        target: /var/log/app
        volume:
          subpath: app        # only the "app" folder inside the volume

Two containers writing the same files at the same time is still the applications' problem to coordinate. Sharing works best when one container writes and the others read.

Adding NAS storage: NFS and SMB shares

A NAS is the natural home for bulk data: media libraries, photos, documents and backup copies. Docker can use a NAS share in two ways, and the choice affects what happens when the NAS is slow, rebooting or offline.

Two ways to use NAS storage over NFS: in option A the host mounts the NAS export at /mnt/nas/media through /etc/fstab and a bind mount passes it into the container; in option B a Docker volume using the local driver with type nfs is mounted by Docker when a container uses it, so the container does not start if the share is unavailable.Two ways to use NAS storage over NFS: in option A the host mounts the NAS export at /mnt/nas/media through /etc/fstab and a bind mount passes it into the container; in option B a Docker volume using the local driver with type nfs is mounted by Docker when a container uses it, so the container does not start if the share is unavailable.

Should databases live on a NAS?

Short answer: no, not for a home lab. Keep live databases on the Docker host's local disk and send backup copies to the NAS. This is the same design as the Docker host weekend project.

The database projects explain why:

  • PostgreSQL treats NFS like a local disk and has firm requirements for it to be safe: the share must be mounted with the hard option, and the NFS server should use the sync export option. Without server-side sync, the documentation says writes the database believes are safe might not reach permanent storage, "which could cause corruption." With hard, processes can hang indefinitely during network problems, so it needs careful monitoring.
  • SQLite, which many self-hosted apps use without telling you, warns that its locking has "been known to operate incorrectly for some network filesystems," leading to corruption. Its advice is to use a client/server database if the data lives on a different machine.

Network storage also adds a dependency: if the NAS reboots for an update, every container using it is affected. For media files that are mostly read, that's an easy trade. For a database that's always writing, it isn't.

Prepare the NFS export on the NAS

Every NAS has its own interface, but the settings to look for are the same:

  1. Create a shared folder for the data, such as media or docker-backups.
  2. Enable NFS and allow access only from your Docker host's IP address, not your whole network.
  3. Choose how user IDs map. NFS sends numeric UIDs and GIDs, so the IDs your containers run as must have permission on the NAS folder. By default, NFS servers apply root squashing: requests from root (UID 0) are mapped to an anonymous user, usually UID 65534. A container running as root often can't write to an NFS share for exactly this reason. Either run the container as a regular user whose UID owns the folder on the NAS, or use the NAS's squash options to map all access to one account.
  4. Note the export path. It's usually shown in the NAS interface, such as /volume1/media.

Avoid no_root_squash unless you understand it: it lets root on any allowed client act as root on the share.

Option A: mount the share on the host, then bind mount it

The host mounts the share at boot, and containers receive a folder inside it as an ordinary bind mount. Host tools, such as backup scripts, can use the same mount.

Install the NFS client and add the share to /etc/fstab:

sudo apt install -y nfs-common
sudo mkdir -p /mnt/nas/media
192.168.1.20:/volume1/media  /mnt/nas/media  nfs  defaults,_netdev,nofail  0  0
sudo mount /mnt/nas/media
findmnt --mountpoint /mnt/nas/media

What the options do, from the Linux manual pages:

  • _netdev marks the mount as needing the network, so systemd waits for the network before mounting it.
  • nofail lets the server finish booting even if the NAS is offline.
  • hard is the Linux default when you don't specify soft: NFS requests are retried indefinitely. The man page warns that soft timeouts "can cause silent data corruption in certain cases," so don't add soft for anything that writes.
  • NFS version: if you don't set nfsvers, the client tries version 4.2 first and negotiates down to what the server supports. Set nfsvers=4.1 or nfsvers=3 only if your NAS needs a specific version.

Now the important part. If the NAS is offline at boot, /mnt/nas/media is still there, as an empty folder on the local disk. A container bind-mounting it starts normally and writes to your local disk. When the NAS comes back, those files are hidden underneath the mount. Docker's default bind propagation (rprivate) also means a container that started before the share mounted keeps seeing the empty local folder until it's recreated.

The fix uses the missing-path behaviour from earlier. Bind mount a subfolder that exists only on the NAS, and tell Compose not to create it:

services:
  media-app:
    volumes:
      - type: bind
        source: /mnt/nas/media/library   # exists only when the share is mounted
        target: /media
        read_only: true
        bind:
          create_host_path: false

When the share is mounted, /mnt/nas/media/library exists and the container starts. When it isn't, the path doesn't exist, the bind mount fails, and the container refuses to start rather than quietly writing to the wrong disk. Once the NAS is back, run sudo mount -a and docker compose up -d.

An alternative is making Docker itself wait for the mount with a systemd drop-in that adds RequiresMountsFor=/mnt/nas/media to docker.service. That's stricter: if the share can't mount, Docker doesn't start at all, which takes down every container on the host, not just the ones that need the NAS. The subfolder check is usually the better trade.

Option B: let Docker mount the share as a volume

Docker's built-in local volume driver can mount NFS itself. It passes the options to the Linux mount system call, so they're the same options you'd use in fstab. Create the volume once from the command line:

docker volume create --driver local \
  --opt type=nfs \
  --opt o=addr=192.168.1.20,nfsvers=4,rw \
  --opt device=:/volume1/media \
  nas-media

Or declare it in Compose:

services:
  media-app:
    volumes:
      - nas-media:/media:ro

volumes:
  nas-media:
    driver: local
    driver_opts:
      type: nfs
      o: "addr=192.168.1.20,nfsvers=4,rw"
      device: ":/volume1/media"

The pieces are:

  • type: nfs chooses the filesystem.
  • o is the mount options. addr is the NAS's IP address. Add nfsvers=4 (or 3) and rw or ro as needed.
  • device is the export path, prefixed with a colon, because the server address is in addr.

Docker mounts the share when a container using the volume starts, not when you create the volume. That has two consequences:

  • A typo shows up late. docker volume create succeeds with a wrong path or address. The error appears when the first container tries to start, so test with a throwaway container: docker run --rm -v nas-media:/mnt alpine ls /mnt.
  • No share, no start. If the NAS is offline, the mount fails and the container doesn't start. That's the safe failure Option A needs extra work to achieve.

Volume options are fixed when a volume is created. If you change driver_opts in Compose, the existing volume keeps its old options. To apply new ones, stop the containers using it, remove the volume with docker volume rm, and run docker compose up -d to recreate it. For a volume like this, removal deletes Docker's record and empty mount point, not the files on the NAS. The data lives in the export.

Docker's own Compose example for NFS uses the soft option. That's fine for read-mostly media, but follow the PostgreSQL guidance above and leave the default hard behaviour in place for anything that writes data you care about.

Which NFS option should you use?

ConsiderationA: host mount + bind mountB: Docker NFS volume
Where the configuration lives/etc/fstab on the hostThe Compose file, so it travels with the stack
Host tools can use the shareYesNot through Docker's mount
Behaviour when the NAS is offlineContainer starts on the empty local folder, unless you add the subfolder checkContainer fails to start
Share used by several stacksEasy, mount onceOne volume per stack, or one external volume
Changing mount optionsEdit fstab and remountRemove and recreate the volume
FitsHosts where scripts and containers share the NASSelf-contained stacks you might move between hosts

Both are sound. If backup scripts on the host also write to the NAS, as in the weekend project, Option A with the subfolder check keeps one mount for everything. If you want each stack to describe all of its own storage, use Option B.

SMB/CIFS shares

Some NAS systems, and all Windows file servers, share folders over SMB rather than NFS. The local driver can mount those too. This example follows Docker's documentation:

docker volume create --driver local \
  --opt type=cifs \
  --opt device=//nas.home.example/media \
  --opt o=addr=nas.home.example,username=docker,password=REPLACE_ME,uid=1000,gid=1000 \
  nas-media-smb

Two details differ from NFS:

  • addr is required when device uses a hostname rather than an IP, so Docker can resolve it.
  • SMB doesn't carry Linux ownership the same way. The uid and gid options set which user owns the files as the container sees them. Match them to the container's user.

Be careful with credentials. Volume options, including the password, are stored by Docker and visible to anyone who can run docker volume inspect. Use a NAS account that can reach only this share. The host-mount approach can keep the password in a root-only credentials file instead, using the credentials= mount option and the cifs-utils package.

Troubleshooting NAS mounts

SymptomLikely causeFix
permission denied writing to the shareRoot squashing, or a UID mismatchRun the container as a UID that owns the NAS folder
Files written to the "NAS" vanished after a rebootThe share wasn't mounted; data went to the local folderUse the subfolder check or Option B; check the local folder for strays
Container hangs, docker stop doesn't workNAS unreachable with a hard mountRestore the NAS or network. Processes resume when it returns
mount.nfs: access denied by serverThe export doesn't allow the host's IPFix the allowed hosts in the NAS's NFS settings
protocol not supportedNFS version mismatchSet nfsvers=3 or 4.1 to match the NAS
Volume changes in Compose have no effectOptions are fixed at creationRemove and recreate the volume
SQLite "database is locked" or corruptionSQLite database on network storageMove the app's database to a local volume

Advanced Docker storage

Image mounts

An image mount makes the filesystem of a second image available read-only inside a container:

docker run --rm -it \
  --mount type=image,src=busybox:musl,dst=/dbg \
  alpine:3.22 /dbg/bin/sh

Docker's documentation suggests three uses: debugging minimal images by mounting a tool-rich image into them, sharing read-only assets such as datasets or models, and keeping application images small by shipping optional tools separately. The mounted image must already exist locally, and there's no -v equivalent.

Image mounts require the containerd image store, described next. Compose supports them with type: image, and the image.subpath option needs Compose 2.35.0 or later.

Storage drivers and the containerd image store

Images and the writable layer are stored by the daemon's storage backend, separately from your volumes. For years that was a storage driver, almost always overlay2 on Linux.

Docker Engine 29.0 changed the default. Fresh installations of Engine 29.0 and later use the containerd image store, which manages images through containerd snapshotters instead of classic storage drivers. Installations upgraded from older versions keep overlay2 until you opt in. Check which one you have:

docker info -f '{{ .DriverStatus }}'

With the containerd store, the output includes io.containerd.snapshotter.v1. Practical differences:

  • Image data moves. Images and container snapshots live under /var/lib/containerd. Volumes and other daemon data stay under /var/lib/docker.
  • It uses more disk. containerd keeps both the compressed and the extracted layers.
  • It enables newer features, such as image mounts.
  • Switching hides existing data. Changing backends temporarily hides images and containers created with the other one. Volumes are unaffected, but plan the switch.
  • It isn't available with user namespace remapping (userns-remap).

To opt in on an upgraded host, add "features": { "containerd-snapshotter": true } to /etc/docker/daemon.json and restart Docker. None of this changes how you use volumes and bind mounts. It matters when you plan disk space and when you move Docker's data.

Moving Docker's data directory

On many servers the root partition is small and a larger data disk is mounted elsewhere. Docker's data location is set with data-root in /etc/docker/daemon.json:

{
  "data-root": "/mnt/docker-data"
}

Stop Docker, copy the existing directory across with permissions preserved, update the setting, then start Docker and check that your containers and volumes are present before deleting the old copy.

With the containerd image store, data-root doesn't move image and container data in /var/lib/containerd. That's set separately, with root in /etc/containerd/config.toml. Docker's documentation also warns against sharing one data directory between daemons, including over NFS. Docker's own data directory belongs on local disk.

Watching disk usage

Images, stopped containers, build cache, logs and volumes all grow. Start with:

docker system df          # summary by type, with reclaimable space
docker system df -v       # per image, container and volume

The verbose view shows each volume's size and how many containers use it, which is the quickest way to find a forgotten anonymous volume that holds gigabytes.

Safe cleanup, roughly from least to most risky:

docker image prune        # dangling images only
docker container prune    # stopped containers
docker builder prune      # build cache
docker volume prune       # unused anonymous volumes

Leave docker volume prune -a and docker system prune --volumes for when you've checked the list and have a backup. If container logs are what's growing, configure log rotation as described in the Compose guide's logging section.

Volume plugins and other filesystems

The local driver handles NFS, CIFS and other filesystems the kernel can mount. Docker's documentation shows it mounting a block device as ext4 and creating a Btrfs-backed volume, though it describes the block-device approach as an example rather than recommended practice.

For storage the kernel can't mount directly, volume plugins add drivers. Docker's documentation uses the rclone plugin as its example, which mounts SFTP and cloud storage as volumes. Plugins run with high privilege on the host, so treat installing one like installing any other root-level software. For most home labs, NFS or SMB through the local driver is enough.

Docker Desktop

On Docker Desktop for Mac and Windows, the Docker daemon runs inside a Linux virtual machine. Named volumes live inside that VM, not in a folder you can browse. Bind mounts of your Mac or Windows folders still work, because Docker Desktop handles sharing them into the VM, but bind propagation options don't work there. Docker's general advice applies: use named volumes when an application needs high-performance I/O, such as a database.

Docker backup strategies

Persistence and backup are different things. A volume survives container updates. It doesn't survive a failed disk, a mistaken down -v, ransomware or a house fire. A backup is a separate copy, kept somewhere the original's failures can't reach, that you've proven you can restore.

Docker backup strategy: live data in volumes and bind mounts is captured consistently, kept as a host copy for fast restores, then copied to a NAS and to an encrypted off-site location; a regular restore test checks the data and feeds fixes back, following the 3-2-1 rule of three copies, two devices and one off-site.Docker backup strategy: live data in volumes and bind mounts is captured consistently, kept as a host copy for fast restores, then copied to a NAS and to an encrypted off-site location; a regular restore test checks the data and feeds fixes back, following the 3-2-1 rule of three copies, two devices and one off-site.

What do you need to back up?

To rebuild a Docker host, you need:

ItemWhyHow
compose.yaml and override filesThe definition of every serviceGit, plus the file backup
.env files and secrets/Passwords and settings that aren't in GitFile backup, plus a password manager copy
Bind-mounted config foldersApplication settingsFile backup
Named volumesApplication dataVolume backup through a container
Database contentsThe most important data, and the easiest to back up badlyThe database's own dump tool
NAS data used by containersMedia and documentsNAS snapshots plus an off-site copy

You don't need to back up images. They can be pulled again, as long as you've pinned versions so you get the same ones. You don't need /var/lib/docker as a whole either: copying it while Docker runs is unreliable, and it's full of data you can recreate.

How do you back up a database running in Docker?

Copying a database's files while it's running doesn't produce a reliable backup. PostgreSQL's documentation says the server "must be shut down in order to get a usable backup" from its files, because a file copy isn't an atomic snapshot of the data. MariaDB, MySQL and most other databases have the same limitation.

You have three consistent options:

  1. Use the database's dump tool. This is the best choice for most home labs. PostgreSQL's pg_dump produces a consistent snapshot while the database stays online. Its documentation says the dump represents the database "at the time pg_dump began running," and doesn't block other operations. MariaDB and MySQL have mariadb-dump and mysqldump.
  2. Stop the service, copy the files, start it again. Simple and consistent, at the cost of a few minutes' downtime.
  3. Take a filesystem snapshot. On ZFS, Btrfs or LVM, an atomic snapshot of the volume's filesystem works while the database runs. PostgreSQL treats a restore from one like recovery from a crash and replays its write-ahead log. Data and logs on separate filesystems must be snapshotted at exactly the same moment.

The Compose guide's reference stack shows a pg_dump backup job as a Compose profile, and the weekend project uses a dump script with a tested restore.

Back up a named volume with a temporary container

For volumes that hold ordinary files, Docker's documentation shows the pattern: start a throwaway container that mounts the volume and a backup folder, and archive one into the other. Stop the service first if it writes constantly:

docker compose stop app

docker run --rm \
  --mount type=volume,src=notes_app_data,dst=/data,readonly \
  --mount type=bind,src="$PWD/backups",dst=/backup \
  alpine:3.22 \
  tar czf /backup/app_data-$(date +%F).tar.gz -C /data .

docker compose start app

The volume is mounted read-only, so the backup container can't change it. The -C /data . stores paths relative to the volume root, which makes restoring into a different volume name straightforward. Create the backups folder first, or the --mount bind fails.

To restore into a new or empty volume:

docker volume create notes_app_data_restored

docker run --rm \
  --mount type=volume,src=notes_app_data_restored,dst=/data \
  --mount type=bind,src="$PWD/backups",dst=/backup,readonly \
  alpine:3.22 \
  tar xzf /backup/app_data-2026-11-20.tar.gz -C /data

Restoring into a new volume rather than over the live one means a bad backup can't make things worse. Point a test copy of the service at the restored volume, check it, and only then switch over.

Migrate volumes to another host

The same pattern moves data between machines: back up on the old host, copy the archive across, restore into a volume with the same name on the new host, then start the stack. Because Compose prefixes volume names with the project name, keep the same name: in the Compose file, or restore into the prefixed name the new project expects. docker compose config --volumes lists the volumes a file defines.

For databases, migrate with a dump and restore rather than copying volume files. It also works across major database versions, which a file copy doesn't.

Follow the 3-2-1 rule

The 3-2-1 rule is a long-standing guideline for backups:

  • 3 copies of your data: the live data plus two backups.
  • 2 different devices or media, so one hardware failure can't take out everything.
  • 1 copy off-site, so a fire, flood or burglary can't either.

In a home lab that usually means:

  1. Dumps and volume archives written to a folder on the Docker host, for fast restores.
  2. A copy on the NAS, which is a second device in the same house.
  3. An encrypted copy somewhere else: a cloud storage bucket, or a NAS at a friend's or family member's house.

Many NAS systems can take scheduled read-only snapshots of shares. Snapshots are excellent protection against accidental deletion and ransomware on the client, because a compromised Docker host can't change a read-only snapshot. They aren't off-site, though, and they fail with the NAS.

Off-site backups with restic

restic is a popular open source tool for the off-site copy. Repositories are encrypted and password-protected, backups are de-duplicated, and it supports many destinations: local folders, SFTP, its own REST server, Amazon S3 and S3-compatible storage, Backblaze B2, Azure, Google Cloud Storage and others through rclone.

A minimal routine, run on the Docker host after the local backup has finished:

export RESTIC_REPOSITORY="sftp:backup@offsite.example:/srv/restic/docker-host"
export RESTIC_PASSWORD_FILE="/root/.restic-password"

restic init                                     # once, to create the repository
restic backup /srv/docker-host /srv/backups     # project folders and dumps
restic forget --keep-daily 7 --keep-weekly 5 --keep-monthly 12 --prune
restic check
  • backup stores a new snapshot. Only changed data is uploaded.
  • forget applies the retention policy, here a week of dailies, five weeklies and a year of monthlies. On its own, forget only removes snapshot records. --prune also deletes the data no snapshot needs any more.
  • check verifies the repository's integrity. restic recommends running it after pruning.

Store the restic password somewhere other than the server, such as your password manager. restic's documentation is clear that losing the password means the data is irrecoverably lost. Borg and Kopia are good alternatives with similar designs, and many NAS systems include their own cloud sync. The tool matters less than having an encrypted copy off-site and testing it.

Schedule backups and prove the restore

A backup routine has three parts, and most home labs stop after the first:

  1. Run it automatically. Use cron or a systemd timer for the dump, the volume archive and the off-site copy, in that order. Log the output somewhere you'll see it.
  2. Alert on failure. A backup that silently stopped running three months ago is the most common way backups fail. A push monitor such as Uptime Kuma's, pinged at the end of a successful run, alerts you when the ping stops. Keep alerts to things someone must act on, as covered in designing actionable alerts.
  3. Restore on a schedule. Every month or so, restore a recent backup into a scratch container or a spare machine, check that the data is there, and note how long it took. Restore from the off-site copy at least occasionally, because that's the one you'll need after a real disaster.

The restore test is the step that turns backup files into a recovery plan. It catches missing volumes, empty dumps, wrong passwords and forgotten .env files while there's still time to fix them.

Putting it together: a stack with every storage type

Here's a reference Compose file for a photo library app with a PostgreSQL database. It uses each storage type for the job it's best at: a local named volume for the database, a bind mount for config, a read-only NFS volume for the photo archive on the NAS, tmpfs for scratch space, and a backup job behind a profile. The ghcr.io/example/photos image is a placeholder. Swap in any app with a similar layout.

name: photos

services:
  app:
    image: ${APP_IMAGE:?Set APP_IMAGE in .env}
    restart: unless-stopped
    user: "1000:1000"
    read_only: true
    depends_on:
      db:
        condition: service_healthy
    environment:
      DB_HOST: db
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    ports:
      - "127.0.0.1:8080:8080"
    volumes:
      - ./config:/config                    # bind mount: settings you edit, backed up with the project
      - app_data:/data                      # named volume: thumbnails, app state
      - photo_archive:/photos:ro            # NFS volume: the NAS archive, read-only
      - type: tmpfs
        target: /tmp
        tmpfs:
          size: 268435456                   # 256 MiB scratch space
    networks:
      - web
      - database

  db:
    image: ${POSTGRES_IMAGE:?Set POSTGRES_IMAGE in .env}   # a 17.x tag for this data path
    restart: unless-stopped
    environment:
      POSTGRES_DB: photos
      POSTGRES_USER: photos
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - db_data:/var/lib/postgresql/data    # local disk; PostgreSQL 18+ mounts /var/lib/postgresql
    networks:
      - database
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
      interval: 10s
      timeout: 5s
      retries: 5

  # On demand or from a timer: docker compose run --rm backup
  backup:
    image: ${POSTGRES_IMAGE:?Set POSTGRES_IMAGE in .env}
    profiles: ["backup"]
    user: "1000:1000"
    depends_on:
      db:
        condition: service_healthy
    environment:
      PGHOST: db
      PGUSER: photos
      PGDATABASE: photos
    secrets:
      - db_password
    volumes:
      - ./backups:/backups
    networks:
      - database
    entrypoint: ["sh", "-c"]
    command:
      - PGPASSWORD="$$(cat /run/secrets/db_password)" pg_dump -Fc -f /backups/photos-$$(date +%F).dump

volumes:
  db_data:
  app_data:
  photo_archive:
    driver: local
    driver_opts:
      type: nfs
      o: "addr=192.168.1.20,nfsvers=4,ro"
      device: ":/volume1/photos"

networks:
  web:
  database:
    internal: true

secrets:
  db_password:
    file: ./secrets/db_password.txt

The decisions worth noticing:

  • The database is on local disk. Only the read-mostly photo archive is on the NAS, and it's mounted read-only twice over: ro in the NFS options and :ro on the service.
  • If the NAS is offline, the app doesn't start, because Docker can't mount the NFS volume. It never writes the archive to the wrong place.
  • The container's root filesystem is read-only. Everything it may write is an explicit mount: config, app data and a size-limited tmpfs. If the app fails to start, its log names the path it couldn't write to.
  • The backup job dumps the database consistently while it runs. The backups and config folders, the .env file and secrets/ are then picked up by the host's file backup and off-site copy. app_data gets the temporary-container archive described above.
  • Pinned images live in .env, so a restore uses the same versions. The comment on db is a reminder to change the data path when you move to PostgreSQL 18.

Treat this as a pattern, not a drop-in file. Check your app's documentation for its real data paths, user requirements and _FILE secret support.

Common Docker storage mistakes and how to fix them

SymptomLikely causeFix
Data gone after an image updateThe app wrote to the container layer, not a mountMount a volume at the app's data path, then restore from backup
Data gone after downdown -v, or the volume was anonymousUse named volumes and plain down; restore from backup
Data gone after a cleanupdocker volume prune -a while the stack was downCheck docker volume ls before pruning; restore from backup
Empty database after renaming the project folderNew project name, new volume namesSet name: in the Compose file; point it back at the old volumes
Database empty after a PostgreSQL 18 upgradeVolume mounted at the 17-style pathMount /var/lib/postgresql, and upgrade with pg_upgrade or dump/restore
Config file mounted as a directoryThe host file didn't exist when the container first startedRemove the directory, create the file, recreate the container
Image's default files missingA bind mount, or a non-empty volume, hides themUse an empty named volume, or copy the defaults in first
permission denied on a mountUID mismatch, root squashing or SELinuxMatch UIDs, run as a non-root user, add z/Z on SELinux hosts
NAS files written to local diskThe share wasn't mounted when the container startedUse a NAS-only subfolder with create_host_path: false, or an NFS volume
Disk full with no obvious causeImages, build cache, logs or orphaned volumesdocker system df -v, then prune selectively
Backups exist but won't restoreFiles copied from a running database, or never testedUse dumps or stopped-service copies, and schedule restore tests

The takeaway

Docker storage comes down to one idea: containers are disposable, so data must live on a mount. Named volumes are the default for application data and databases. Bind mounts are for files you want to see and edit on the host. tmpfs is for scratch space that should never persist.

Network storage earns its place for bulk files such as media and backups, not live databases. Mount NFS shares so a missing share stops a container instead of silently redirecting its writes: either a Docker NFS volume, or a host mount with a NAS-only subfolder and create_host_path: false.

Persistence isn't protection. Back up with tools that produce consistent copies, keep three copies on two devices with one off-site, and restore a backup on a schedule. Be most careful with commands that remove volumes, especially down -v and volume prune -a, because they're the quickest way to need that backup.

If you haven't built your Docker host yet, start with the weekend project, which puts these ideas into practice with a tested restore. To tighten up the Compose files that define your mounts, see the Docker Compose beginner-to-expert guide.

References