备份 Docker 运行的 WordPress 网站需要考虑两部分:文件系统和数据库。以下是几种可靠的备份方法:
# 查找 WordPress 容器挂载的卷
docker inspect <wordpress_container_name> | grep "Source"
# 复制整个 WordPress 目录到备份位置
cp -r /var/lib/docker/volumes/<wordpress_volume>/_data /path/to/backup/wordpress_files
# 导出数据库
docker exec <mysql_container_name> mysqldump -u root -p<password> wordpress > /path/to/backup/wordpress_db.sql
docker run --rm --volumes-from <wordpress_container_name> -v /path/to/backup:/backup ubuntu tar cvf /backup/wordpress_backup.tar /var/www/html
docker run --rm --volumes-from <mysql_container_name> -v /path/to/backup:/backup ubuntu tar cvf /backup/mysql_backup.tar /var/lib/mysql
创建 backup.sh
脚本:
#!/bin/bash
# 定义变量
BACKUP_DIR="/path/to/backup"
DATE=$(date +%Y-%m-%d_%H-%M-%S)
MYSQL_CONTAINER="<mysql_container_name>"
MYSQL_USER="root"
MYSQL_PASSWORD="<password>"
MYSQL_DATABASE="wordpress"
WORDPRESS_CONTAINER="<wordpress_container_name>"
# 创建备份目录
mkdir -p $BACKUP_DIR/$DATE
# 备份数据库
docker exec $MYSQL_CONTAINER mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE > $BACKUP_DIR/$DATE/wordpress_db.sql
# 备份 WordPress 文件
docker run --rm --volumes-from $WORDPRESS_CONTAINER -v $BACKUP_DIR/$DATE:/backup ubuntu tar czvf /backup/wordpress_files.tar.gz /var/www/html
echo "Backup completed at $BACKUP_DIR/$DATE"
Docker 卷备份工具:
docker run --rm -v <volume_name>:/volume -v /path/to/backup:/backup loomchild/volume-backup backup <archive_name>
使用 Duplicati:
docker run --rm --volumes-from <wordpress_container_name> -v /path/to/backup:/backup ubuntu bash -c "rm -rf /var/www/html/* && tar xvf /backup/wordpress_files.tar.gz -C /var/www/html --strip 1"
cat /path/to/backup/wordpress_db.sql | docker exec -i <mysql_container_name> mysql -u root -p<password> wordpress
您可以根据实际需求选择最适合的备份方案。对于生产环境,建议采用自动化备份方案并定期测试恢复流程。