Skip to content

Instantly share code, notes, and snippets.

@iconnor
Created July 31, 2023 00:43
Show Gist options
  • Save iconnor/e2a0b42abfa5f967ec3dd0bee914fbff to your computer and use it in GitHub Desktop.
Save iconnor/e2a0b42abfa5f967ec3dd0bee914fbff to your computer and use it in GitHub Desktop.
Move docker with the least downtime possible
#!/bin/bash
# Check if a command line argument is provided
if [ -z "$1" ]
then
# If not, prompt the user to enter the target directory
echo "Please enter the target directory:"
read -r target_dir
else
# If an argument is provided, use it as the target directory
target_dir=$1
fi
# Calculate used space in /var/lib/docker (in KB)
used_space=$(du -sk /var/lib/docker | cut -f1)
# Calculate available space in the target directory (in KB)
available_space=$(df -k "$target_dir" | tail -1 | awk '{print $4}')
# Check if there's enough available space on the target disk
if (( available_space < used_space )); then
echo "Not enough space on the target disk"
exit 1
fi
echo 'Enough space on the target disk, running initial sync'
# First run sync to do most of the copying while the service is running
rsync -az --info=progress2 /var/lib/docker "$target_dir"
# Stop docker
systemctl stop docker
# Catch up the last few changes
echo 'Stopping docker, running final sync'
rsync -az --info=progress2 /var/lib/docker "$target_dir"
echo 'Final sync complete, restarting docker with new data directory'
# Create a new docker.service file with -g /data1/docker added to the ExecStart line
cp /lib/systemd/system/docker.service /tmp/docker.service
sed -i "s|^ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock$|& -g $target_dir|g" /tmp/docker.service
# Move over the prepared directory with -g /data1/docker added to the ExecStart line
cp /tmp/docker.service /lib/systemd/system/docker.service
# Reload systemd, enable and start the service
systemctl daemon-reload
# Start docker
systemctl start docker
echo 'Docker restarted - once you have confirmed everything is working, you can delete the old data directory /var/lib/docker'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment