To back up a WordPress website, you need to backup two components:
- database: posts, pages, categories, comments, users, plugin data, etc.
- filesystem: media, plugins, files, etc.
Here we see how to backup and restore a WordPress instance via command line both in pure-bash fashion and also wordpress is running on docker.
Backup/Restore via bash
First, create a config file to source for variables. Remember this file must stay private.
WP_DATA_DIR=/var/www/html/wp-content
# provide DB name, user and pass
DB_NAME=dbname
DB_USER=dbuser
DB_PASS=dbpassword
# etc ..
Backup
Here is how to backup the DB (mysql, mariadb)
/usr/bin/mysqldump \
-u $_DB_USER \
-p$_DB_PASSWORD \
$_DB_NAME \
> ${DB_BACKUP_FILE}
And here is how to backup a WordPress instance.
# WP_DATA_DIR=/var/www/html/wp-content
tar czpf $BAK_TARGET_DIR/$WP_BACKUP_NAME.tar.gz $WP_DATA_DIR
Note: I usually backup only the wp-content
folder, and not the full content of server’s /var/www/html/
Restore
Database
cat "$DB_BACKUP_FILE" | /usr/bin/mysql -u$_DB_USER -p$_DB_PASSWORD $_DB_NAME
WordPress files
# WP_DATA_DIR=/var/www/html/wp-content
tar xzpf backup/$_WP_BACKUP_NAME -C / #$WP_DATA_DIR
Backup/Restore on Docker
In this section, we’ll see how to backup DB and filesystem of a wordpress instance running on docker. The main big difference with the bash version, is that we need to spin a container to backup/restore.
Bash inside docker
To execute a script in a container, we first need to get the container id, using docker ps
.
Then, below you see a trivial way to execute a command inside a container.
docker exec -it <CONTAINER_ID> bash -l
Of course, we won’t backup via bash in the container, but this might be useful just to get a grip of the situation.
Backup
Here is how to backup the db on a running container.
# perform database backup
docker exec $DB_IMAGE_NAME /usr/bin/mysqldump \
-u $DB_USER \
-p$DB_PASSWORD \
$DB_NAME \
> ${DB_BACKUP_FILE}
DB_IMAGE_NAME
: name of the image running the container
And here is how we backup the WP data.
# wordpress data backup
docker run --rm --volumes-from $WP_IMAGE_NAME \
-v $BAK_TARGET_DIR:/backup ubuntu \
tar czpf /backup/$WP_BACKUP_NAME.tar.gz $WP_DATA_DIR
WP_IMAGE_NAME
: name of the image running the containerWP_DATA_DIR
: directory you want to backup inside the container, i.e./var/www/site/public_html
Restore
Here is the restore of the DB.
# restore database
cat "$DB_SOURCE_FILE" | docker exec -i $DB_IMAGE_NAME \
/usr/bin/mysql -u$DB_USER -p$DB_PASSWORD $DB_NAME
And this is how I restore the WordPress data
# restore wordpress files
docker run --rm \
--volumes-from $WP_IMAGE_NAME \
-v $BAK_SOURCE_DIR:/backup \
ubuntu \
tar xzpf backup/$WP_BACKUP_NAME -C / #$WP_DATA_DIR
Conclusion
This approach works and is the actual method I am using for this site, although I automated a bit the process.
0 Comments