How to change docker root data directory and why would you want to do that (hint: to optimize space)

Context

I have a small vps for some personal projects which has 20 gb storage. I have one project there, and a few day ago I no longer had any available space. That meant docker services went down (and so the small project). I knew the project should not use that much space, and I found out that docker was using around 10gb space for overlay2.

The whole overlay2 situation is enough for another post, but I found out (after researching and reading a lot of articles) that it grows pretty fast, and it is really hard to clean. òverlay2 is one of the ways docker synchronizes the filesystem, and it duplicates data.

I decided to change the root data directory (by default at /var/lib/docker) to another volume attached to my vps, which I can increase in space if needed.

Steps

Important:

Make a backup of all your information (volumes, containers and everything that you cannot automatically generate again.)

1. Stop docker service

sudo systemctl stop docker

on older systems

sudo service docker stop

2. Edit etc/docker/daemon.json or create it if it does not exist

nano /etc/docker/daemon.json

Add the following line if empty

{ 
   "data-root": "/path/to/your/new/docker/root"
}

or, if there is already something there, add just the key, appending a comma in the previous line

"data-root": "/path/to/your/new/docker/root"

so that is looks like this:

{
  "another-key": "another value", 
  "data-root": "/path_to_new_root/docker"
}

Important

  • This will change your data directory, not move it. Your data will not be there when you restart the docker service. All the containers and volumen will be created from zero.
  • This will recreate the whole docker data directory structure on the destination, as docker need it to run properly.
  • Doing this is similar to removing all your containers, volumes and so on. (although in this case they are still on the old directory until you remove them manually)
  • If you use a volume, another hard-drive or similar as the new destination, make sure it has enough free space available. I would recommend no less than 10 gb for small projects, with the possibility of increasing it.

3. Restart docker

sudo systemctl restart docker

or, on older systems

sudo service docker start

4. Rebuild your projects and restore backups if necessary

If you use docker-compose for your projects, just run docker compose up -d --build.

If you have database and data backups, restore them.


With this you have now changed the root data directory from /var/lib/docker to /path_to_new_root/docker

References

Comments

Comments powered by Disqus