Docker is a very handy tool to replicate the running environment for your server. The caching mechanism of container building is also brilliant. However, it comes with a cost, you usually run out of disk space.

To mitigate the issue and optimize the disk for other development tasks, I usually separate a volume for docker. Here is how. If you want to clean unused docker resource, scroll to the end of the post and check the commands.

Change docker home directory

  • Open /lib/systemd/system/docker.service and edit the line starting with ExecStart=....
    Old: ExecStart=/usr/bin/dockerd -H fd://
    New: ExecStart=/usr/bin/dockerd -g /mnt/87927e5c-4678-4d7d-9625-e7bb907ed0d9/docker -H fd://

Where /mnt/87927e5c-4678-4d7d-9625-e7bb907ed0d9/docker is the new home for the docker service. The default directory is at /var/lib/docker.

  • Next, run systemctl stop docker && systemctl daemon-reload && systemctl start docker.
  • To check if there is no problem with the new configuration: systemctl status docker.

Migrate old docker data before changing

If you want to migrate the old docker data (volume, image, container, etc...), simply move the old data to the new location. Specifically,

  • Stop docker for the migration: systemctl stop docker.
  • Migrate the data mv /var/lib/docker /mnt/87927e5c-4678-4d7d-9625-e7bb907ed0d9/docker.
  • Edit the docker service unit file as explained in the previous section, and the next steps remaining the same.

Automatically mounting volume/partition on startup

If you specified the new docker home to a directory in a secondary hard disk. After each restart, by default, you need to manually mount the disk. Otherwise, docker will not start. To enable the automatic mounting.

  • Open the "Disks" application, by searching for disk.
  • Select the secondary hard disk, then select the partition where the new docker's home directory belongs to. Click the double gears icon. Choose "Edit Mount Options...".
  • Check "Mount at system startup". And click "OK".

Clean docker resource

To clean unused docker resources: stopped containers, images, unused networks, etc. Note: volumes are not removed by this command.

docker system prune -af

To clean unused docker volumes:

docker volume prune -af