Business tech · Intermediate · 25 min
How to Back Up and Restore a WordPress Site with WP-CLI
By Padding · Updated 16 Nov 2026
Ubuntu 26.04.1 LTS · WordPress 7.1.4 · WP-CLI 2.12.0
You will write a backup script that saves a WordPress 7.1 site's database and wp-content folder to a private folder with WP-CLI 2.12, schedule it with cron, prune old copies, then destroy the demo database and restore it from the backup to prove that the backup works.
On this page
A WordPress site is two things that must be saved together: a database, which holds your posts, pages, comments, users and settings, and files, which hold your uploads, themes and plugins in the wp-content folder. The WordPress core code is not part of the backup. You can download it again, and the same version, whenever you like. A backup that has only one of the two is half a backup, and a backup you have never restored is a hope, not a backup.
This tutorial uses WP-CLI to do both halves. You write a script that saves them into a private folder, schedule it with cron, and keep two weeks of copies. Then you test the one thing that matters: you wipe the demo database and the uploaded file, restore them, and check that the site is back. Do this on a site you can afford to break. If your site holds real content, the restore test belongs on a copy of it on another machine.
It builds on the WordPress install tutorial, and uses the same paths: the site is in /var/www/wordpress, WordPress runs as the user wordpress, and WP-CLI is installed as /usr/local/bin/wp.
Step 1 · Check what you are backing up
Before you back anything up, look at the site. WP-CLI reads wp-config.php for the database login, so run it as the wordpress user from the site folder. Note the version, the size of the database and how much space the wp-content folder takes. You use these numbers to plan disk space:
cd /var/www/wordpress
sudo -u wordpress wp core version
sudo -u wordpress wp db size --human-readable
sudo du -sh /var/www/wordpress/wp-contentThe version starts with 7.1., the database is likely under a few MB for a new site, and wp-content is small until you upload media. For a real site, the uploads folder is usually the largest part and decides how long a backup takes and how much room you need.
Make some content to protect: a published post, and a file in the uploads folder standing in for a picture. Both will be gone and then restored in the last steps:
cd /var/www/wordpress
sudo -u wordpress wp post create --post_title='Backup test post' --post_name=backup-test --post_status=publish --porcelain
sudo -u wordpress mkdir -p wp-content/uploads
echo "uploaded file contents" | sudo -u wordpress tee wp-content/uploads/proof.txtThe first command prints the new post's ID, a number such as 5. The tee command shows the line it wrote, uploaded file contents.
Step 2 · Make a private folder for backups
A backup holds everything an attacker wants: password hashes, private posts and, with wp-config.php, the database password and the secret keys. Treat the folder like a secret. Create it owned by root, with no access for anyone else. The wordpress user, which runs your site's PHP code, must not be able to read or delete the backups: a flaw in one plugin runs as that user, and it should not be able to reach the copies you will need after an attack:
sudo install -d -o root -g root -m 0700 /var/backups/wordpress
sudo ls -ld /var/backups/wordpressThe listing shows drwx------ and the owner and group root. Because only root can open this folder, every command below that reads it uses sudo, including the globs: sudo ls /var/backups/wordpress/db-* would fail, since your own shell expands the * before sudo runs, and cannot see inside.
Step 3 · Write the backup script
Put the logic in a script, so a person and a scheduler run exactly the same thing. It saves three files per run, each stamped with the time: the database (compressed), the wp-content folder and wp-config.php (compressed), and a note of the WordPress version, which you will need to rebuild the site. At the end it deletes anything older than 14 days:
sudo tee /usr/local/sbin/wp-backup > /dev/null <<'SH'
#!/usr/bin/env bash
# Back up the WordPress site in /var/www/wordpress: database and wp-content.
# Run as root: the backups belong to root. WP-CLI itself runs as the wordpress user.
set -euo pipefail
umask 077
SITE=/var/www/wordpress
DEST=/var/backups/wordpress
KEEP_DAYS=14
WP=/usr/local/bin/wp
STAMP="$(date +%Y%m%d-%H%M%S)"
cd "$SITE"
# Database: --single-transaction gives a consistent snapshot without locking the site.
runuser -u wordpress -- "$WP" db export --single-transaction --add-drop-table - | gzip > "$DEST/db-$STAMP.sql.gz.partial"
mv "$DEST/db-$STAMP.sql.gz.partial" "$DEST/db-$STAMP.sql.gz"
# Files: everything in wp-content except caches, plus the configuration.
tar -czf "$DEST/files-$STAMP.tar.gz.partial" -C "$SITE" --exclude=wp-content/cache wp-content wp-config.php
mv "$DEST/files-$STAMP.tar.gz.partial" "$DEST/files-$STAMP.tar.gz"
# The core version, so the same release can be downloaded when rebuilding.
runuser -u wordpress -- "$WP" core version > "$DEST/version-$STAMP.txt"
# Delete copies older than KEEP_DAYS.
find "$DEST" -maxdepth 1 -type f \( -name 'db-*.sql.gz' -o -name 'files-*.tar.gz' -o -name 'version-*.txt' \) -mtime +"$KEEP_DAYS" -delete
echo "Backup $STAMP done"
SH
sudo chown root:root /usr/local/sbin/wp-backup
sudo chmod 755 /usr/local/sbin/wp-backup
bash -n /usr/local/sbin/wp-backup && echo "script syntax ok"The decisions in it:
- The script, the backup folder and the backups all belong to root, and the job runs as root. The
wordpressuser cannot rewrite the script, read the backups or delete them. Only the WP-CLI calls drop to thewordpressuser withrunuser, because WP-CLI refuses to run as root and reads the credentials as the site's own user. set -euo pipefailstops at the first error, andumask 077makes every file private. Files are written with a.partialsuffix and renamed only when complete, so a backup that was cut short never looks like a good one.- The script calls
/usr/local/bin/wpby its full path, becausecronruns with a shortPATHthat does not include/usr/local/bin. - The
find ... -deleteline only touches files in the backup folder that match the three name patterns. Read any command that deletes before you change it. wp-config.phpgoes in the archive so the database credentials and keys are saved too. The backup folder is private for that reason, and you should encrypt copies you send elsewhere.
Step 4 · Run a backup and check it
Run the script as root:
sudo /usr/local/sbin/wp-backup
sudo ls -l /var/backups/wordpressThe script prints Backup <timestamp> done, and the folder has three files, db-<stamp>.sql.gz, files-<stamp>.tar.gz and version-<stamp>.txt, and nothing ending in .partial. They are all mode -rw-------.
Check that the pieces are readable and complete. gzip -t and tar -t read the whole file and report damage. The grep looks for the table that holds your posts in the SQL, and cat prints the saved version:
sudo sh -c 'cd /var/backups/wordpress &&
gzip -t db-*.sql.gz && echo "database file is intact" &&
tar -tzf files-*.tar.gz | grep -E "wp-config.php|uploads/proof.txt" &&
zcat db-*.sql.gz | grep -c "CREATE TABLE \`wp_posts\`" &&
cat version-*.txt'sudo sh -c '...' runs the whole quoted script as root, so the shell that expands db-* can open the folder.
You see database file is intact, the two paths wp-config.php and wp-content/uploads/proof.txt, a count of 1, and the version number. A file that is quietly empty or truncated is the classic way a backup job fails without anyone noticing, so build this check into your routine.
Step 5 · Schedule it with cron
A backup that depends on you remembering is not a backup. Cron runs jobs on a schedule, as covered in the cron tutorial. A file in /etc/cron.d/ names the user that runs the job. This one runs at 03:17 every night as root and appends its output to a log in the backup folder:
sudo tee /etc/cron.d/wordpress-backup > /dev/null <<'CRON'
# Nightly WordPress backup at 03:17, run as root
17 3 * * * root /usr/local/sbin/wp-backup >> /var/backups/wordpress/backup.log 2>&1
CRON
sudo chmod 644 /etc/cron.d/wordpress-backup
cat /etc/cron.d/wordpress-backupCron picks up the new file by itself, with no reload. Files in /etc/cron.d/ must be owned by root and not writable by others, and their names may use only letters, digits, underscores and hyphens, or cron ignores them. Pick an odd minute such as 17 rather than 00, so you do not compete with every other job on the hour.
Check on it the next morning and, from then on, now and then: sudo ls -l /var/backups/wordpress should show a new set each day, and sudo tail /var/backups/wordpress/backup.log should end in done. That log only ever grows, a few lines a night, so add it to a logrotate rule when you have time: stop log files filling your disk with logrotate. If you can, let a monitor tell you when a night is missed, as in alerting with Alertmanager.
Step 6 · Copy the backup off the server
A backup on the same disk as the site disappears with it when the disk fails, the server is deleted, or an intruder wipes the folder. Keep at least one copy somewhere else, such as a second server or object storage. For a second server you reach over SSH, rsync copies only what changed. Replace the user, host and folder with yours:
sudo rsync -a --chmod=D700,F600 /var/backups/wordpress/ backupuser@backup.example.com:wordpress-backups/Running rsync as root needs an SSH key in root's account, restricted on the receiving side to that one job, as in log in with SSH keys. Because the backup includes secrets, encrypt it before it leaves the server if the destination is not yours alone. Add the copy as a second line in the script or as another cron entry a few minutes after the backup. Also set the receiving side so the backup user can add files but cannot delete old ones, so a stolen key cannot erase your history.
Step 7 · Practice the restore
This is the part people skip, and the reason backups fail when they are needed. Do it now, on a site you can afford to lose.
Before you destroy anything, find the backup files and prove they are usable. Resolving the names comes first, because the next step is destructive. The folder belongs to root, so the lookup runs inside sudo sh -c and the file names are stored in shell variables. Then gzip -t and tar -t read both files end to end:
DB_FILE="$(sudo sh -c 'ls -t /var/backups/wordpress/db-*.sql.gz | head -n 1')"
FILES="$(sudo sh -c 'ls -t /var/backups/wordpress/files-*.tar.gz | head -n 1')"
if [ -n "$DB_FILE" ] && [ -n "$FILES" ] && sudo gzip -t "$DB_FILE" && sudo tar -tzf "$FILES" > /dev/null; then
echo "ready to restore from $DB_FILE and $FILES"
else
echo "No usable backup found. Do not continue."; false
fiThe output is ready to restore from and the two file names. If you see No usable backup found, stop and fix the backup first. The next commands would otherwise destroy a site you cannot restore.
Now the damage: delete the database tables with WP-CLI, and remove the uploaded file. wp db reset drops every table in the WordPress database. Run it only against the demo site. The if repeats the guard, so it does nothing when the variables are empty:
cd /var/www/wordpress
if [ -n "$DB_FILE" ] && [ -n "$FILES" ]; then
sudo -u wordpress wp db reset --yes
sudo rm /var/www/wordpress/wp-content/uploads/proof.txt
else
echo "Backup files are not set. Nothing was changed."; false
fi
sudo -u wordpress wp core is-installed || echo "site is gone"You see Success: Database reset. and then site is gone. If you open the site in a browser now, WordPress offers to install itself again.
Restore the database first. wp db import - reads the SQL from standard input. sudo gunzip -c reads the root-owned file and decompresses it into the pipe. The backup was made with --add-drop-table, so it replaces any tables that exist:
cd /var/www/wordpress
sudo gunzip -c "$DB_FILE" | sudo -u wordpress wp db import -It ends with Success: Imported from 'STDIN'. Now restore the files. sudo cat reads the archive as root, and tar runs as the wordpress user so the restored files have the right owner. It overwrites wp-content and wp-config.php with the saved versions:
sudo cat "$FILES" | sudo -u wordpress tar -xzf - -C /var/www/wordpressCheck it worked
Ask WordPress, the database and the file system:
cd /var/www/wordpress
sudo -u wordpress wp core is-installed && echo "WordPress is installed again"
sudo -u wordpress wp post list --post_type=post --fields=post_title,post_status --format=csv
cat /var/www/wordpress/wp-content/uploads/proof.txt
sudo -u wordpress wp db checkYou see WordPress is installed again, the post Backup test post as publish (next to the sample post that WordPress creates), the file contents uploaded file contents, and Success: Database checked. after a line for each table. If the site uses a domain, open it in a browser and look at the post.
Restoring on a new server
The same pieces rebuild a site elsewhere. Follow the WordPress install tutorial up to and including the database and WP-CLI steps. Then:
- Download the same core version that the backup records:
sudo -u wordpress wp core download --version=$(sudo cat /var/backups/wordpress/version-<stamp>.txt), with the stamp of the backup you restore. The backup folder belongs to root, so the read needssudo; copy the files to the new server first, for example to/var/backups/wordpressthere, as the off-server step does in reverse. - Import the database as above, into the new empty database.
- Extract the
filesarchive into/var/www/wordpressas thewordpressuser. Then create a freshwp-config.phpwithwp config createas in the install tutorial, so the new server's database password is used and not the old one. - If the domain changed, update the stored addresses:
sudo -u wordpress wp search-replace 'https://old.example.com' 'https://new.example.com' --all-tables --dry-runshows what would change, and running it again without--dry-runmakes the change. - Run the checks in the last step.
Troubleshooting
Error: Database connection errorduring a backup: the script runs WP-CLI as thewordpressuser, and the credentials come fromwp-config.php. Run the script by hand withsudo /usr/local/sbin/wp-backupto see the real error.wp: command not foundin the cron log: the script callswpby name. Use the full path, as in the script above.- The backup folder is empty or the log is missing: the cron file has a wrong owner or mode, or a name with a dot in it. Cron ignores such files silently, so check
ls -l /etc/cron.d. mysqldump: Got error ... when using LOCK TABLES: the database user lacks a privilege.--single-transactionavoids table locks; the user needsSELECTandLOCK TABLESon the database, which the user from the install tutorial has throughALL PRIVILEGESon its own database.- You run out of disk: lower
KEEP_DAYS, exclude cache folders, or move old copies off the server. Look for the biggest files with the disk space tutorial.
Step 8 · Remove the demo
If this was a practice site, remove the schedule, the script and the backups. This deletes every backup in the folder:
sudo rm /etc/cron.d/wordpress-backup /usr/local/sbin/wp-backup
sudo rm -r /var/backups/wordpress
cd /var/www/wordpress
sudo -u wordpress wp post delete $(sudo -u wordpress wp post list --name=backup-test --field=ID) --force
sudo rm /var/www/wordpress/wp-content/uploads/proof.txtIf you also want to remove the whole demo site, follow the cleanup step of the install tutorial.
Next steps
- Set the site up in the first place: install WordPress on Ubuntu 26.04 with Nginx.
- Learn the scheduler: schedule jobs with cron.
- Do the same for a different database: back up and restore PostgreSQL with pg_dump.
- Move to a new host: move a website to a new host without downtime.
Related tutorials
- How to Schedule Jobs with Cron on LinuxYou will schedule a command to run every minute, then on a real timetable, read the cron syntax, and learn why a job that works in your shell can fail under cron.
- How File Permissions Work in Linux: chmod, chown and umaskYou will read Linux permission strings, change them with chmod and chown, set up a folder two users can share, and control the defaults with umask.
- How to Back Up and Restore a PostgreSQL Database with pg_dumpYou will back up a PostgreSQL 18 database in three formats, restore it into a fresh database, check the copy matches, and schedule a nightly backup that deletes old files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials