Linux containers part three


OK, you now have a bunch of containers running on one (or more) hosts, how to back them up?

Best (in my opinion) option is to use filesystem snapshot, available with LVM, ZFS and BTRS back end storage.

Please test with disposable container before relying on this technique for vital data.

In outline the process is:

  1. Take snapshot of the container using lxc snapshot.
  2. Publish the container as an image, lxc publish.
  3. Export the published image, lxc image export.
  4. Assuming a successful export, delete the published image and snapshot.

The resulting image export file can be restored using lxc image import but please note the restriction;

Directory import is only available on Linux and must be performed as root

This backup process is easily wrapped up in a script which can then be scheduled for a regular container backup.

#!/bin/bash
# backup-containers.sh
# Use LXC snapshot to backup running containers to destination of your choice.
# (c) Alan jeskins-Powell (Bespoke IT Solutions) 2019
# Reproduced here for anyone to use - at your own risk!
# *****
# Script provided As Is.
# No warranty, either express or implied.
# In no event shall the author be responsible for any claim, damages or other liability
# arising from, out of or in connection with this script.
# *****

# Optional parameter = container name to backup
# Default is empty, i.e. all containers will be backed up.
containerPattern=${1:-""}
echo "Using container pattern: ${containerPattern}"

# Destination directory for image exports
backupDir=/backup/lxc-export
# Timestamp for backup
backupTimestamp=`date +%Y%m%d%H%M`

# Logging function
log()
{
echo -e "`date +%Y%m%d%H%M%S`: ${1}"
}

# Use lxc list to read and process all container names
while read container
do
  backupContainerName=${backupTimestamp}-${container}
  log "===="
  log "Starting backup container ${container} ..."
  log "> Using backup container name: ${backupContainerName}"
  log "> Container snapshot ..."
  lxc snapshot ${container} ${backupContainerName}
  log "> Save snapshot as image ..."
  lxc publish ${container}/${backupContainerName} --alias ${backupContainerName}-image --verbose
  log "> Export image (this may take a while) ..."
  lxc image export ${backupContainerName}-image ${backupDir}/${backupContainerName} --verbose
  log "> Delete backup image ..."
  lxc image delete ${backupContainerName}-image
  log "> Delete backup snapshot ..."
  lxc delete ${container}/${backupContainerName}
done < <( lxc list ${containerPattern} --format csv --columns n )

# Keep 2 days backups available
echo "Rempoving backups > 2 days old ..."
find ${backupDir} -name \*.tar.gz -mtime +2 -exec rm -vf {} \; -ls
Comment on this article using form below. Requires email login only for authentication. HTML forbidden, Markdown only.