How to declare docker volumes to exist on an external hardrive in docker compose

Viewed 1713

Due to space limitations on my local machine I need to ensure my docker containers store their data on my external hard drive.

The docker project I am using has a docker compose file and it specifies a number of volumes like so:

version: "2"
volumes:
  pgdata:
  cache:
services:
  postgres:
    image: "openmaptiles/postgis:${TOOLS_VERSION}"
    volumes:
      - pgdata:/var/lib/postgresql/data

Those volumes ultimately exist on my local machine. I'd like to change their location to somewhere on my external drive e.g /Volumes/ExternalDrive/docker/

How do I go about this?

I have read the docker documentation on volumes and and docker-compose but can't find a way to specify the path of where a volume should exist.

If anyone could point the way I would be most grateful.

1 Answers

You can explore and test more features related to volumes using the CLI help and then transpose to compose.

docker volume create --help

https://docs.docker.com/engine/reference/commandline/volume_create/


Note that example below might not work on Windows hence the built-in local driver on Windows does not support any options, but if you're running docker on Linux, the compose file below should do the job:

version: "2"
volumes:
  pgdata:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/path/to/the/external/storage'
  cache:

services:
  postgres:
    image: "openmaptiles/postgis:${TOOLS_VERSION}"
    volumes:
      - pgdata:/var/lib/postgresql/data


You might also consider to change the docker launch options to store its data in a location of your choice. Here's a guide: https://linuxconfig.org/how-to-move-docker-s-default-var-lib-docker-to-another-directory-on-ubuntu-debian-linux


Alternatively, if you're more comfortable trying to solve this in the OS rather than docker, you could try some tricks at the filesystem level to create a symbolic link at /var/lib/docker/volumes/ to point at your external storage, but be careful and backup everything. I personally never tried this, but I believe it should be transparent for the docker storage driver.

Related