Docker Planka: Backup database and files

If you have Planka running Dockerized, you are likely using the docker-backup.sh which is provided by https://github.com/plankanban/planka

Changes from the original script:
– Docker swarm compatibility (Filters container name)
– CD into script’s directory (For when you use this with cron tasks)
– Removed UTC date format to raw date output from system
– Deletes any old .tgz files after creating the new backup

Variables to set:
SCRIPT_DIRECTORY=”/script/location”
BACKUP_DATETIME=$(date +%Y-%m%d-%H%M)
BACKUP_TMPDIR=$(mktemp -d planka-backup-XXXXXX)
BACKUP_FILENAME=”${BACKUP_DATETIME}-planka.tgz”
OLD_BACKUP_FILES=(*-planka.tgz)

#!/bin/bash

set -e

# Location for this script
SCRIPT_DIRECTORY="/home/btro/docker_planka"

# CD to script's directory (for cron compatibility)
cd "${SCRIPT_DIRECTORY}"

# Other environment variables to set
BACKUP_DATETIME=$(date +%Y-%m%d-%H%M)
BACKUP_TMPDIR=$(mktemp -d planka-backup-XXXXXX)
BACKUP_FILENAME="${BACKUP_DATETIME}-planka.tgz"
OLD_BACKUP_FILES=(*-planka.tgz)

PLANKA_DOCKER_CONTAINER_POSTGRES=$(docker ps --filter "name=^planka_postgres" --format "{{.Names}}" | head -n1)
PLANKA_DOCKER_CONTAINER_PLANKA=$(docker ps --filter "name=^planka_planka" --format "{{.Names}}" | head -n1)

if [[ -z "$PLANKA_DOCKER_CONTAINER_POSTGRES" ]]; then
    echo "Error: No running planka_postgres container found!"
    exit 1
fi
if [[ -z "$PLANKA_DOCKER_CONTAINER_PLANKA" ]]; then
    echo "Error: No running planka_planka container found!"
    exit 1
fi

# Export DB
echo -n "Exporting postgres database ... "
docker exec -t "$PLANKA_DOCKER_CONTAINER_POSTGRES" pg_dumpall -c -U postgres > "$BACKUP_TMPDIR/postgres.sql"
echo "Success!"

# Export Docker volumes
for item in favicons user-avatars background-images attachments; do
    # Source path
    SRC="/app/public/$item"
    [[ "$item" = "attachments" ]] && SRC="/app/private/attachments"
    echo -n "Exporting $item ... "
    docker run --rm --user $(id -u):$(id -g) \
        --volumes-from "$PLANKA_DOCKER_CONTAINER_PLANKA" \
        -v "$(pwd)/$BACKUP_TMPDIR:/backup" ubuntu \
        bash -c "[ -d $SRC ] && cp -r $SRC /backup/$item || echo 'No $item to backup.'"
    echo "Done!"
done

# Fix permissions (optional but robust)
chown -R $(id -u):$(id -g) "$BACKUP_TMPDIR"

# Create final archive (everything in the temp dir, no extra folder in archive)
echo -n "Creating tarball $BACKUP_FILENAME ... "
tar -czf "$BACKUP_FILENAME" -C "$BACKUP_TMPDIR" .
echo "Success!"

# Remove temp dir
rm -rf "$BACKUP_TMPDIR"

# Delete previous backup(s) (except the newly created one)
for file in "${OLD_BACKUP_FILES[@]}"; do
    if [[ "$file" != "$BACKUP_FILENAME" && -f "$file" ]]; then
        echo "Deleting previous backup: $file"
        rm -f "$file"
    fi
done

echo "Backup Complete! Archive is at $BACKUP_FILENAME"