---
# System prepended metadata

title: Untitled

---

## Requirements
- jq
- docker-machine

## Usage
```dockup.sh instance stack```

## Code

```shell
#!/bin/bash

# Directory to save the backup on the remote server
REMOTE_BACKUP_DIR="/tmp"

# Directory to save the backup on the local machine
LOCAL_BACKUP_DIR="./"

# Instance name in docker-machine
INSTANCE_NAME="$1"

# Stack name in your Docker Swarm
STACK_NAME="$2"

eval $(docker-machine env ${INSTANCE_NAME})

# Docker volumes directory
DOCKER_ROOT_DIR=$(docker info --format '{{.DockerRootDir}}')
DOCKER_VOLUME_DIR="${DOCKER_ROOT_DIR}/volumes"

# Find all services in the stack
SERVICES=$(docker stack services ${STACK_NAME} --format '{{.Name}}')

# Create instance directory
mkdir -p ${INSTANCE_NAME}

echo "$SERVICES"
# Iterate over all services
for SERVICE in $SERVICES
do
    echo "Backing up service: ${SERVICE}"

    # Find all volumes of the service
    VOLUMES=$(docker service inspect ${SERVICE} --format '{{ json .Spec.TaskTemplate.ContainerSpec.Mounts }}' | jq -r '.[] | select(.Type == "volume") | .Source')

    # Iterate over each volume and backup
    for VOLUME in $VOLUMES
    do
        echo "Backing up volume: ${VOLUME}"

        # Create a backup filename
        REMOTE_BACKUP_FILE="${REMOTE_BACKUP_DIR}/${SERVICE}_${VOLUME}_$(date +%Y%m%d%H%M%S).tar.gz"
        LOCAL_BACKUP_FILE="${LOCAL_BACKUP_DIR}/${INSTANCE_NAME}/${SERVICE}_${VOLUME}_$(date +%Y%m%d%H%M%S).tar.gz"

        # Use docker run to start a temporary container with the volume attached, and create a tar.gz file of the volume's contents
        docker-machine ssh ${INSTANCE_NAME} "docker run --rm -v ${DOCKER_VOLUME_DIR}/${VOLUME}/_data:/volume alpine tar czf - -C /volume . > ${REMOTE_BACKUP_FILE}"

        # Transfer the backup file to the local machine
        docker-machine scp ${INSTANCE_NAME}:${REMOTE_BACKUP_FILE} ${LOCAL_BACKUP_FILE}
    done
done

```