Moving Docker data to a new directory
As it’s only disk was running out of space I bought a second disk for my server, and planned to move at least my Docker data there as that was one of the bigger directories on the disk.
Most manuals I found just tell you to stop Docker, copy the data, change the config and start Docker again but that led to issues in my situation, so here are the steps I needed to take to get this to work properly on my Ubuntu server running Docker CE:
Stop Docker:
sudo systemctl stop docker
sudo systemctl stop docker.socket
If you run the first command it will print this: Warning: Stopping docker.service, but it can still be activated by: docker.socket
This means that Docker will be restarted once something connects to the socket (it’s running ‘on demand), which for example running docker ps
would do. We really want Docker to be disabled during the copy process so we also disabled the socket.
Now that Docker won’t write to the data files any more we can copy them:
rsync -avPHSX /var/lib/docker/ /mnt/newdisk/docker-data
The important flag for my installation which is not in most examples is the H
as it makes sure to copy hardlinks as hardlinks (credit) , which the overlay system of Docker uses.
Once the data has been copied, you can change the config to point to the right location. For this the file to change is usually /etc/docker/daemon.json
and there you add a line for data-root
:
{
"data-root": "/mnt/newdisk/docker-data",
...
}
Starting Docker after these steps for me resulted in issues of hardly any Docker containers having started, which turned out to be because the configuration in config.v2.json
for the others was pointing to the old data directory (source). Luckily the page I found also contains a oneliner to fix this:
sed -i 's%/var/lib/docker%/mnt/newdisk/docker-data%g' /mnt/newdisk/docker-data/containers/*/config.v2.json
You can run this without -i
to first verify what’s it’s going to do.
Now to be sure that if you start Docker again it’s really using the new location you can rename the old one:
mv /var/lib/docker /var/lib/docker-old
Now start Docker again:
sudo systemctl start docker
And everything should work as before.