Docker Data Directory Migration Script
This Bash script moves the Docker data directory from the default location (/var/lib/docker) to a new directory (e.g. /home/docker), ensuring that Docker is reconfigured and restarted correctly.
The script must be run by the root or sudo user.
📁 Script Purpose
- Stop Docker safely
- Copy Docker data to a new directory using
rsync - Update Docker daemon config (
daemon.json) - Start Docker with the new data root
- Verify and remove the old directory if successful
✅ Requirements
- OS: Debian/Ubuntu
- Docker installed
- Sudo privileges
rsync(installed by the script if missing)
⚙️ Configuration Variables
| Variable | Default Value | Description |
|---|---|---|
NEW_DOCKER_DIR |
/home/docker |
New location for Docker data |
OLD_DOCKER_DIR |
/var/lib/docker |
Default Docker data location |
DOCKER_CONFIG |
/etc/docker/daemon.json |
Docker configuration file |
DOCKER_CONFIG_BAK |
Timestamped backup of the config | Stored in the same folder |
Step-by-Step Behavior
1. Install rsync (if missing)
if ! command -v rsync >/dev/null 2>&1; then
sudo apt update
sudo apt install -y rsync
fi
2. Create Target Directory
sudo mkdir -p /home/docker
3. Stop Docker
Stops both docker.socket and docker service:
sudo systemctl stop docker.socket || true
sudo systemctl stop docker
4. Copy Docker Data
All files from the old Docker directory are copied with permissions preserved:
sudo rsync -aP /var/lib/docker/ /home/docker/
5. Backup and Update daemon.json
Creates a backup if the config file exists and rewrites it to use the new data root:
sudo cp /etc/docker/daemon.json /etc/docker/daemon.json.bak.YYYYMMDDHHMMSS
echo '{ "data-root": "/home/docker" }' | sudo tee /etc/docker/daemon.json
6. Restart Docker
sudo systemctl start docker
7. Verify Configuration
Checks if Docker is using the new root path:
docker info | grep -q "Docker Root Dir: /home/docker"
If verified:
- Deletes the old directory
- Prints success message
Otherwise:
- Prints error
- Advises to restore from the backup
🔁 Restore Instructions (if needed)
If Docker doesn't start correctly or the new path doesn't apply:
sudo cp "$DOCKER_CONFIG_BAK" "$DOCKER_CONFIG"
sudo systemctl restart docker
🛉 Cleanup
Only if verification is successful:
sudo rm -rf /var/lib/docker
💡 Notes
- The script uses
set -eto exit on error — it will stop on any failed command unless explicitly ignored (e.g.,|| true). - It is safe to re-run — idempotent for most actions.
- All actions are logged to the terminal for easy tracking.
📌 Example Usage
Run the script with bash or chmod +x and execute directly:
chmod +x migrate-docker-root.sh
./migrate-docker-root.sh
Changelog
| Date | Author | Message |
|---|---|---|
| 2026-02-25 | aresnikowa | Merge remote-tracking branch 'origin/master' |