Docker uses a default storage location to store image and container data. If the default storage location is running low on space, or if you want to store your images and container data on a different hard drive, you can follow the steps below to change the storage location for images and containers:
-
Verify the current location and stop the Docker service
By default, Docker stores its images and container data in the/var/lib/docker
directory. To verify the current storage location, execute the commanddocker info | grep "Docker Root Dir"
. Before changing the storage location, you need to stop the Docker service. Enter the following command in the terminal to stop Docker:1
sudo systemctl stop docker
-
Create a directory for Docker data
Create a directory on the new hard drive to store Docker’s data. You can use themkdir
command to create this directory. For example, if you want to store Docker data in the/mnt/new_location
directory, you can use the following command:1
sudo mkdir -p /mnt/new_location/docker
This command creates a subdirectory named
docker
under/mnt/new_location
. You can change the directory path and name as needed. -
Copy existing Docker data to the new directory
If you want to copy the existing Docker data to the new directory, you can use thersync
command. For example, if the current Docker data is stored in the/var/lib/docker
directory, you can copy the data to the new directory using the following command:1
sudo rsync -axP /var/lib/docker/ /mnt/new_location/docker/
This command will copy all files and subdirectories from
/var/lib/docker
to/mnt/new_location/docker/
. The time this process takes will depend on the size of the data and the speed of your hard drive. -
Change the Docker configuration file
Next, you need to change Docker’s configuration file so that Docker uses the new storage location. Edit the/etc/docker/daemon.json
file and add the following content:1 2 3
{ "data-root": "/mnt/new_location/docker" }
This configuration file instructs Docker to use the
/mnt/new_location/docker
directory as its new storage location. -
Restart the Docker service
Finally, restart the Docker service to apply the changes. Enter the following command in the terminal to restart Docker:1
sudo systemctl start docker
You can run the command
docker info | grep "Docker Root Dir"
again to see if the directory change has taken effect.
Now, Docker will use the new storage location to store images and container data. If you want to move Docker data back to the default location, simply change the data-root
property in the daemon.json
file back to /var/lib/docker
.