How to back up and restore Drupal 8 (Part 2)

This is the fourth chapter of the Drupal 8 Theming: Getting Started series. In this chapter you are going to back up and restore the database you created in the first chapter of this series.

Backing up and restoring the Drupal 8 database

In addition to the backup of the Drupal 8 directory, you have to save all the data your site is working with. In the first chapter of this series, you created a database named d8basics, so that what you are going to do now is to back up all the data within it. Let’s begin!

1. Start your MySQL Server, open a command line window and then change to the directory where mysqldump (which is a database backup program) is located (in my case, it is located in xampp \ mysql \ bin).

I am running the mysqldump executable file from “C:\xampp\mysql\bin” because I haven’t added this path to the system environment variable PATH. If you want to run mysqldump from everywhere in the system, add “C:\xampp\mysql\bin” to the system environment variable PATH.

2. To create a backup of the d8basics database in the tmp folder with the root user, run the following command:

mysqldump -u root -p d8basics > C:\Users\xus\Downloads\tmp\db_backup.sql

The previous command assumes that the database is on your computer. If it were on a remote computer (e.g., db0000.mysqlserver.com), then the previous command would be rewritten as follows:

mysqldump -u root -h db0000.mysqlserver.com -p d8basics > C:\Users\xus\Downloads\tmp\db_backup.sql

3. As you can see in the previous image, there is no news about the execution of the mysqldump command and no news is good news. If you change to the tmp directory, you will see that the backup has been successfully created.

4. Now that you have a backup of the database your Drupal 8 site is working with, let’s simulate a loss of data by destroying all the tables in the database. In order to delete the d8basics database completely, that is, every table therein and all its data, run the following query:

DROP DATABASE d8basics;

5. If you try to use the d8basics database now, you will not able to do it because it does not exist any longer.

6. And, of course, if you try to navigate to your Drupal 8 site, you will get the following error: The website encountered an unexpected error. Please try again later.

7. In order to restore the database your Drupal 8 site is working with, you have to create the d8basics database again and then import all the tables into it. To create the d8basics database again, run the following query:

CREATE DATABASE d8basics CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

To import all the tables in the d8basics database, run the following command:

mysql -u root -h localhost -p d8basics < C:\Users\xus\Downloads\tmp\db_backup.sql

As you can see in the following image, the database has been successfully restored.

For more information about how to back up and restore a MySQL database, click me.