Last active
November 2, 2024 03:22
-
-
Save dinomite/b516e835b09ea08526ff17114979900f to your computer and use it in GitHub Desktop.
Simple script to backup LXC containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -ex | |
BACKUP_DIR=/path/to/where/backups/should/live | |
HOSTS=($(lxc list -c n --format csv)) | |
for HOST in "${HOSTS[@]}" | |
do | |
BACKUP_NAME=${HOST}-$(date +"%Y-%m-%d") | |
lxc snapshot ${HOST} auto-backup | |
lxc publish ${HOST}/auto-backup --alias ${BACKUP_NAME} | |
lxc image export ${BACKUP_NAME} ${BACKUP_DIR}/${BACKUP_NAME} | |
lxc image delete ${BACKUP_NAME} | |
lxc delete ${HOST}/auto-backup | |
done |
Tested today and importing on another host works with this sequence:
# Import the image
lxc image import <tarball> --alias <image_alias>
# Create the container from the image
lxc init <image_alias> <container_name>
# Start the container
lxc start <container_name>
For example, I started my nginx container on a new host with:
lxc image import nginx-2020-01-01.tar.gz.tar.gz --alias nginx-copy
lxc init nginx-copy nginx-copy
lxc start nginx-copy
I use UFW rules to route from the host interface to the container setup the rules:
# /etc/ufw/before.rules
*nat
:PREROUTING ACCEPT [0:0]
# nginx container
-A PREROUTING -i eno1 -p tcp --dport 80 -j DNAT --to <container_ip>:80
-A PREROUTING -i eno1 -p tcp --dport 443 -j DNAT --to <container_ip>:443
COMMIT
# Remainder of file unchanged
…and turn on UFW:
sudo ufw enable
When I edit /etc/ufw/before.rules
, I use this one-liner to reload the firewall rules:
for i in $( sudo iptables -t nat --line-numbers -L | grep ^[0-9] | awk '{ print $1 }' | tac ); do sudo iptables -t nat -D PREROUTING $i; done; sudo ufw reload
Awesome :)
One question though.. Will this also re add devices back to the container's config that you've added with:
lxc config device add c1 sharedwww disk source=/wwwdata/ path=/var/www/html/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmmm, I think I tested unpacking the image on another host and it started right up. Since you're achieving your new year's resolutions early maybe a test of your backups are in order to confirm my memory! (that'd be a good thing for met to check, too)