Specify docker storage directory
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 resources, scroll to the end of the post and check the commands.
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.
Change docker home directory
- Open, or create if not exist, the file at
/etc/docker/daemon.json
. - Add the following key/value in the json format.
{
"data-root": "/mnt/87927e5c-4678-4d7d-9625-e7bb907ed0d9/docker"
}
Where
is the new home for the docker service. The default directory is at /mnt/87927e5c-4678-4d7d-9625-e7bb907ed0d9/docker
/var/lib/docker
.
- Next, run
systemctl restart docker
. - To check if there is no problem with the new configuration:
systemctl status docker
.
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