dockerdocker-for-maccolima

How to migrate volume data from docker-for-mac to colima


How do I move volumes from docker-for-mac into colima?


Solution

  • Will copy all the volumes from docker-for-mac and move them to colima.

    Note: there will be a lot of volumes you may not want to copy over since they're temporary ones, you can ignore them by simply adding a | grep "YOUR FILTER" to the for loop, either before or after the awk.

    The following code makes 2 assumptions:

    1. you have docker-for-mac installed and running
    2. you have colima running

    That is all you need, now copy-and-paste this into your terminal. No need to touch anything.

    (
    # set -x  # uncomment to debug
    set -e
    
    # ssh doesn't like file descriptor piping, we need to write the configuration into someplace real
    tmpconfig=$(mktemp);
    
    # Need to have permissions to copy the volumes, and need to remove the ControlPath and add ForwardAgent
    (limactl show-ssh --format config colima | grep -v "^  ControlPath\|  ^User"; echo "  ForwardAgent=yes") > $tmpconfig;
    
    # Setup root account
    ssh -F $tmpconfig $USER@lima-colima "sudo mkdir -p /root/.ssh/; sudo cp ~/.ssh/authorized_keys /root/.ssh/authorized_keys"
    
    # Loop over each volume inside docker-for-mac
    for volume_name in $(DOCKER_CONTEXT=desktop-linux docker volume ls | awk '{print $2}'); do 
        echo $volume_name;
    
        # Make the volume backup
        DOCKER_CONTEXT=desktop-linux docker run -d --rm --mount source=$volume_name,target=/volume --name copy-instance busybox sleep infinate; 
        DOCKER_CONTEXT=desktop-linux docker exec copy-instance sh -c "tar czf /$volume_name.tar /volume";
        DOCKER_CONTEXT=desktop-linux docker cp copy-instance:/$volume_name.tar /tmp/$volume_name.tar; 
        DOCKER_CONTEXT=desktop-linux docker kill copy-instance;
    
        # Restore the backup inside colima
        DOCKER_CONTEXT=colima docker volume create $volume_name;
        ssh -F $tmpconfig root@lima-colima "rm -rf /var/lib/docker/volumes/$volume_name; mkdir -p /var/lib/docker/volumes/$volume_name/_data";
        scp -r -F $tmpconfig /tmp/$volume_name.tar root@lima-colima:/tmp/$volume_name.tar;
        ssh -F $tmpconfig root@lima-colima "tar -xf /tmp/$volume_name.tar --strip-components=1 --directory /var/lib/docker/volumes/$volume_name/_data";
        
    done
    )