QR Barcode Maker - illi.io

How to Migrate Docker Data Directory to a New Path (with Automation Script)

Category: Scripts · Published on 2025-09-12

This article provides an enhanced Docker data migration script with strict pre-checks, safety validations, and automatic dependency installation.

Recommended Method: Run Online Script

The easiest way is to run the script online without downloading manually:

bash <(curl -sSL https://reshub.cn/data/sh/docker-move.sh)
Tip: Ensure you have root privileges and sufficient disk space before running.

Migration Steps

  1. Stop the Docker service
  2. Perform pre-checks and validate the new path
  3. Migrate data with rsync while preserving attributes
  4. Backup the old directory
  5. Update /etc/docker/daemon.json configuration
  6. Restart Docker and verify the migration

Full Script (for reference)

#!/bin/bash
# Docker data migration script (general version with strict checks)
# Usage: sudo ./docker-move.sh /data1/docker
set -euo pipefail

NEW_PATH=${1:-}
DOCKER_SERVICE="docker"
DOCKER_DIR="/var/lib/docker"
CONFIG_FILE="/etc/docker/daemon.json"

ALLOW_NONEMPTY="${ALLOW_NONEMPTY:-0}"

die() { echo -e "\n[ERROR] $*\n" >&2; exit 1; }
info(){ echo "[INFO]  $*"; }
warn(){ echo "[WARN]  $*"; }

require_root() {
  [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Please run as root (sudo)."
}

require_new_path() {
  [[ -n "$NEW_PATH" ]] || die "Please specify the new Docker data directory. Usage: sudo $0 /data1/docker"
  [[ "$NEW_PATH" == /* ]] || die "The new path must be absolute: $NEW_PATH"
  [[ -d "$DOCKER_DIR" ]] || die "Old directory not found: $DOCKER_DIR. Docker installation missing."

  if [[ "$NEW_PATH" == "$DOCKER_DIR" ]]; then
    die "New path cannot be the same as old path: $NEW_PATH"
  fi
  if [[ "$NEW_PATH" == "$DOCKER_DIR"* ]]; then
    die "New path cannot be inside old path: $NEW_PATH in $DOCKER_DIR"
  fi
  if [[ "$DOCKER_DIR" == "$NEW_PATH"* ]]; then
    die "Old path cannot be inside new path: $DOCKER_DIR in $NEW_PATH"
  fi

  mkdir -p "$NEW_PATH" || die "Failed to create new path: $NEW_PATH"
  chown root:root "$NEW_PATH" || die "Failed to set owner: $NEW_PATH"
  if [[ "$ALLOW_NONEMPTY" != "1" ]]; then
    if [[ -d "$NEW_PATH" ]] && [[ -n "$(ls -A "$NEW_PATH" 2>/dev/null || true)" ]]; then
      die "New directory must be empty (or set ALLOW_NONEMPTY=1 to override): $NEW_PATH"
    fi
  fi
}

require_cmds() {
  command -v docker >/dev/null 2>&1 || die "docker command not found. Please install Docker."
  if ! command -v rsync >/dev/null 2>&1; then
    warn "rsync not found, trying to install..."
    if [[ -f /etc/debian_version ]]; then
      apt update && apt install -y rsync || true
    elif [[ -f /etc/redhat-release ]]; then
      yum install -y rsync || dnf install -y rsync || true
    elif [[ -f /etc/alpine-release ]]; then
      apk add --no-cache rsync || true
    fi
  fi
  command -v rsync >/dev/null 2>&1 || die "rsync installation failed. Please install manually."
}

check_space() {
  local used avail need parent
  used=$(du -sb "$DOCKER_DIR" 2>/dev/null | awk '{print $1}')
  [[ -n "$used" && "$used" -gt 0 ]] || die "Failed to calculate space usage of $DOCKER_DIR."

  parent="$NEW_PATH"
  [[ -d "$parent" ]] || parent="$(dirname "$NEW_PATH")"

  avail=$(df -P -B1 "$parent" 2>/dev/null | awk 'NR==2{print $4}')
  [[ -n "$avail" && "$avail" -gt 0 ]] || die "Failed to get available disk space for $parent."

  local need1 need2 GiB2
  GiB2=$((2*1024*1024*1024))
  need1=$(( (used * 110 + 99) / 100 ))
  need2=$(( used + GiB2 ))
  need=$(( need1 > need2 ? need1 : need2 ))

  info "Old directory used: $used bytes; Available: $avail bytes; Required: $need bytes"
  [[ "$avail" -ge "$need" ]] || die "Insufficient space (need $need, available $avail)."
}

check_selinux() {
  if command -v getenforce >/dev/null 2>&1; then
    local mode
    mode=$(getenforce 2>/dev/null || echo "")
    if [[ "$mode" == "Enforcing" ]]; then
      cat >&2 <<'EOF'

[ERROR] SELinux is in Enforcing mode. Please set proper label for new directory first:
  semanage fcontext -a -t container_var_lib_t "/newpath(/.*)?"
  restorecon -Rv /newpath
EOF
      exit 1
    fi
  fi
}

check_daemon_json() {
  if [[ -f "$CONFIG_FILE" ]]; then
    if command -v jq >/dev/null 2>&1; then
      if ! jq -e '.' "$CONFIG_FILE" >/dev/null 2>&1; then
        local bak="${CONFIG_FILE}.bak.$(date +%Y%m%d%H%M%S)"
        cp -a "$CONFIG_FILE" "$bak" || true
        die "$CONFIG_FILE is not a valid JSON, backed up to: $bak"
      fi
    else
      warn "jq not installed, cannot validate JSON config."
    fi
  fi
}

preflight_checks() {
  info "Performing pre-checks..."
  require_root
  require_cmds
  require_new_path
  check_space
  check_selinux
  check_daemon_json
  info "All pre-checks passed ✅"
}

stop_docker() {
  if command -v systemctl &>/dev/null; then
    systemctl stop "$DOCKER_SERVICE" || true
    systemctl stop "${DOCKER_SERVICE}.socket" || true
  elif command -v service &>/dev/null; then
    service "$DOCKER_SERVICE" stop || true
  else
    die "No systemctl or service command found."
  fi
}

start_docker() {
  if command -v systemctl &>/dev/null; then
    systemctl daemon-reexec || true
    systemctl start "$DOCKER_SERVICE"
  elif command -v service &>/dev/null; then
    service "$DOCKER_SERVICE" start
  else
    die "No systemctl or service command found."
  fi
}

preflight_checks
stop_docker
mkdir -p "$NEW_PATH"
chown root:root "$NEW_PATH"
rsync -aHAX --numeric-ids --delete --info=progress2 "$DOCKER_DIR/" "$NEW_PATH/"
if [[ -d "$DOCKER_DIR" ]]; then
  mv "$DOCKER_DIR" "${DOCKER_DIR}.bak.$(date +%Y%m%d%H%M%S)"
fi
mkdir -p "$(dirname "$CONFIG_FILE")"
if [[ -f "$CONFIG_FILE" && command -v jq >/dev/null 2>&1 ]]; then
  tmp="${CONFIG_FILE}.tmp"
  jq '. ["data-root"] = "'$NEW_PATH'"' "$CONFIG_FILE" > "$tmp" 2>/dev/null || {
    bak="${CONFIG_FILE}.bak.$(date +%Y%m%d%H%M%S)"
    cp -a "$CONFIG_FILE" "$bak" || true
    echo '{"data-root":"'$NEW_PATH'"}' > "$tmp"
  }
  mv "$tmp" "$CONFIG_FILE"
else
  echo '{"data-root":"'$NEW_PATH'"}' > "$CONFIG_FILE"
fi
start_docker
if docker info >/dev/null 2>&1; then
  docker info | grep -E "Docker Root Dir:\s+$NEW_PATH" >/dev/null 2>&1 \
    && echo "Verification passed: Docker Root Dir is now $NEW_PATH" \
    || die "Verification failed: Docker Root Dir is not $NEW_PATH"
else
  die "docker info failed, please check Docker."
fi

echo "Migration completed! Old data has been backed up to: ${DOCKER_DIR}.bak.*"
👁 Views: 13
👎 Dislike 0