Managing Databases
local graph
Chapter 13 — Managing Databases
Section titled “Chapter 13 — Managing Databases”The Linux platform has long been a very popular choice for hosting databases. Given the fact that databases power a large majority of popular websites across the internet nowadays, this is a very important role for servers to fill. Ubuntu Server is also a very popular choice for this purpose, as its stability is a major benefit to the hosting community. This time around, we’ll take a look at MariaDB, a popular fork of MySQL. The goal won’t be to provide a full walkthrough of MySQL’s syntax (as that would be a full book in and of itself), but we’ll focus on setting up and maintaining database servers utilizing MariaDB, and we’ll even go over how to set up a primary/secondary relationship between them. If you already have a firm understanding of how to architect databases, you’ll still benefit from this chapter as we’ll be discussing Ubuntu’s implementation of MariaDB in particular, which has its configuration organized a bit differently than in other platforms.
As we work through setting up our very own MariaDB server, we will cover the following topics:
- Preparations for setting up a database server
- Installing MariaDB
- Understanding the MariaDB configuration files
- Managing MariaDB databases
- Setting up a secondary database server
As with setting up any server for a particular purpose, we should first think about the goal and plan accordingly. So in the next section, we’ll talk about some of the higher-level details to consider while preparing a database server.
Preparations for setting up a database server
Section titled “Preparations for setting up a database server”Before we get started with setting up our database server, there are a few odds and ends to get out of the way. As we go through this chapter, we’ll set up a basic database server using MariaDB. I’m sure more than a few of my readers are familiar with MySQL. MySQL is a tried and true solution that is still in use in many data centers today, and that will probably continue to be the case for the foreseeable future. There’s a good chance that a popular website or two that you regularly visit utilizes it on the backend. So, you may be wondering then, why not go over that instead of MariaDB?
There are two reasons why this book will focus on MariaDB. First, the majority of the Linux community is migrating over to it (more on that later), and it’s also a drop-in replacement for MySQL. This means that any databases or scripts you’ve already written for MySQL will most likely work just fine with MariaDB, barring some edge cases. In reverse, the commands you practice with MariaDB should also function as you would expect on a MySQL server. This is great, considering that many MySQL installations are still in use in many data centers, and you’ll be able to support those too. For the most part, there are very few reasons to stick with MySQL when your existing infrastructure can be ported over to MariaDB, and that’s the direction the Linux community is headed toward anyway.
Why the change? A while back, various distributions of Linux started switching to MariaDB from MySQL. Red Hat is one such example; it switched to MariaDB back in version 7 of Red Hat Enterprise Linux. Other distributions, such as Arch Linux and Fedora, went down the same route. This was partly due to a lack of trust in Oracle, the company that now owns MySQL. When Oracle became the owner of MySQL, there were some serious questions raised in the open source community regarding the future of MySQL as well as its licensing. I’m not going to get into any speculation about Oracle, the future of MySQL, or any politics regarding its future since it’s not relevant to this book (and I’m not a fan of corporate drama). The fact, though, is that many distributions are moving toward MariaDB, and that seems to be the future. It’s a great technology, and I definitely recommend it over MySQL for several reasons that are unrelated to current controversies.
MariaDB is more than just a fork of MySQL. On its own, it’s a very competent database server. The fact that your existing MySQL implementations should be compatible with it eases adoption. But more than that, MariaDB makes some very worthwhile changes and improvements to MySQL that will only benefit you.
Everything you love about MySQL can be found in MariaDB, plus some cutting-edge features that are exclusive to it. But even better is the fact that MariaDB features additional clustering options that are leaps and bounds better and more efficient than plain old MySQL.
So, hopefully I’ve sold you on the value of MariaDB. Ultimately, whether or not you actually use it will depend on the needs of your organization. I’ve seen some organizations opt to stick with MySQL, if only for the sole reason that it’s what they know. I can understand that if a solution has proven itself in your data center, there’s really no reason to change if your database stack is working perfectly fine the way it is. To that end, while I’ll be going over utilizing MariaDB, it’s possible that the examples may work for MySQL as well. If in doubt, MariaDB is recommended for the examples in this chapter.
With regard to your server, a good implementation plan is key (as always). I won’t spend too much time on this aspect, since by now I know you’ve probably been through a paragraph or two in this book where I’ve mentioned the importance of redundancy (and I’m sure I’ll mention redundancy again a few more times before the last page). At this point, you’re probably just setting up a lab environment or test server on which to practice these concepts before using your newfound skills in production. But when you do eventually roll out a database server into production, it’s crucial to plan for long-term stability. Database servers should be regularly backed up, redundant (there I go again), and regularly patched. Later on in this chapter, I’ll walk you through setting up a secondary database server, which will take care of the redundancy part.
However, that’s not enough on its own, as regular backups are important. There are many utilities that allow you to do this, such as mysqldump, and you can also take snapshots of your virtual machine (assuming you’re not using a physical server). Both solutions are valid, depending on your environment. As someone who has lost an entire workday attempting to resurrect a fallen database server for a client (of which they had no backups or redundancy), my goal is simply to spare you that headache.
As far as how many resources a database server needs, that solely depends on your environment. MariaDB itself does not take up a huge amount of resources, but as with MySQL, your usage is dependent on your workload. Either you’ll have a few dozen clients connecting, or a few thousand, or more. But one recommendation I’ll definitely make is to use Logical Volume Manager (LVM) for the partition that houses your database files. This will certainly spare you grief in the long run. As we’ve discussed in Chapter 9, Managing Storage Volumes, LVM makes it very simple to expand a filesystem, especially on a virtual machine.
If your database server is on a virtual machine, you can add a disk to the volume group and expand it if your database partition starts to get full, and your customers will never notice there was ever about to be a problem. Without LVM, you’ll need to shut down the server, add a new volume, rsync your database server files over to the new location, and then bring up the server. Depending on the size of your database, this situation can span hours. Do yourself a favor, use LVM.
With that out of the way, we can begin setting up MariaDB. For learning and testing purposes, you can use pretty much any server you’d like: physical, virtual, or a Virtual Private Server (VPS). Once you’re ready, let’s move on and we’ll get started!
Installing MariaDB
Section titled “Installing MariaDB”Now we’ve come to the fun part, installing MariaDB. To get the ball rolling, we’ll install the mariadb-server package:
sudo apt install mariadb-serverIf your organization prefers to stick with MySQL, the package to install is mysql-server instead:
sudo apt install mysql-serverAlthough it might be tempting to try out both MySQL and MariaDB to compare and contrast their differences, I don’t recommend switching from MariaDB to MySQL (or vice versa) on the same server. I’ve seen some very strange configuration issues occur on servers that had one installed and then were switched to the other (even after wiping the configuration). For the most part, it’s best to pick one solution per server and stick with it. As a general rule, MySQL should be used if you have legacy databases to support. For brand-new installations, go with MariaDB.
After you install the mariadb-server package, check to make sure the service started and is enabled. By default, it should already be running:
systemctl status mariadbNext, we’ll want to add some security to our MariaDB installation (even though we’re using MariaDB, the name of the following command hasn’t been updated and still includes mysql in the name):
sudo mysql_secure_installationAt this point, we haven’t set a root password yet, so go ahead and just press Enter when the script asks for it. This script will ask you additional questions. You will be asked if you’d like to switch to unix_socket authentication. The default answer for this question is yes, but I recommend answering no to this question. This will ensure password authentication is used, which is going to be better for compatibility. There is a security benefit by switching to unix_socket authentication, but for our purposes password authentication will suffice. If you decide to dive into the subject of database management, switching to unix_socket authentication might be better in the future.
Continuing, the mysql_secure_installation script will ask you if you want to set a root password. The root user for MariaDB is not the same as the root user on your system, and you definitely should create a password for it. So when this comes up, press y to tell it you want to create a root password, then enter that password twice.
After setting the root password, the script will ask you whether you’d like to remove anonymous users, and also disallow remote access to the database server. You should answer yes to both. The latter is especially important, as there’s almost never a situation in which allowing public access to MySQL/MariaDB is a good idea. Even if you’re hosting a website for external users, those users only need access to the website, not the database server. The website itself will interface with the database locally as needed; an external connection wouldn’t be necessary. (If you have a standalone database server that’s not publicly accessible to the internet, then you will want to answer yes here – just make sure that the database server can’t be reached publicly). Continuing for the most part, just answer yes to everything the script asks you (unless you have a good reason not to).
The entire process after executing mysql_secure_installation looks like the following, and I’ve included the responses I recommend for each (“y” for yes, “n” for no):
Enter current password for root (enter for none):Switch to unix_socket authentication [Y/n] nSet root password? [Y/n] yRemove anonymous users? [Y/n] yDisallow root login remotely? [Y/n] yRemove test database and access to it? [Y/n] yReload privilege tables now? [Y/n] yAt this point, we officially have a fully functional database server. The previous command allowed us to apply some basic security, and our database server is now available to us. To connect to it and manage it, we’ll use the mariadb command to access the MariaDB shell, where we’ll enter commands to manage our database(s). There are actually two methods to connect to this shell. The first method is by simply using the mariadb command with sudo:
sudo mariadbThis particular command works because if you use the mariadb command as root (we used sudo in this example) the password is bypassed. In fact, we didn’t even enter the username either; root is assumed if you are attempting to access MariaDB with sudo. This is by far the simplest way to connect. However, some of you may be accustomed to a different method of authentication if you’ve used other Linux distributions: entering the username and password. In that case, the command will look like this (it won’t work by default though):
mariadb -u root -pWhen that command works correctly, it will ask you for your root password and then let you into the shell.
It’s recommended to create a different user in order to manage your MariaDB installation, as logging in as root is not recommended in most cases. We’ll be creating additional users later on in this chapter, but for now, the root account is the only one we have available. It’s common practice to use the root account to do the initial setup, and then create a different user for administrative purposes going forward. However, the root account is still often used for server maintenance, so use your best judgment.
So, now that we have access to the MariaDB shell, what can we do with it? The commands we’ll execute on this shell allow us to do things such as create and delete databases and users, add tables, and so on. The mariadb command comes from the mariadb-client-10.6 package, which was installed as a dependency when we installed mariadb-server. Entering the mariadb command by itself with no options connects us to the database server on our local machine. This utility also lets us connect to external database servers to manage them remotely, which we’ll discuss later.
The MariaDB shell prompt will look like this:
MariaDB [(none)]>We’ll get into MariaDB commands and user management later. For now, you can exit the shell. To exit, you can type exit and press Enter or press Ctrl + d on your keyboard.
Now, our MariaDB server is ready to go. While you can now move on to the next section, you might want to consider setting up another MariaDB server by following these steps on another machine. If you have room for another virtual machine, it might be a good idea for you to get this out of the way now, since we’ll be setting up a secondary database server later.
Understanding the MariaDB configuration files
Section titled “Understanding the MariaDB configuration files”Now that we have MariaDB installed, let’s take a quick look at how its configuration is stored. While we won’t be changing much of the configuration in this chapter (aside from adding parameters related to setting up a secondary database instance), it’s a good idea to know where to find the configuration, since you’ll likely be asked by a developer to tune the database configuration at some point in your career. This may involve changing the storage engine, buffer sizes, or countless other settings. A full walkthrough on performance tuning is outside the scope of this book, but it will be helpful to know how the settings for MariaDB are read, since Ubuntu’s implementation is fairly unique.
The configuration files for MariaDB are stored in the /etc/mysql directory. In that directory, you’ll see the following files by default:
debian.cnfdebian-startmariadb.cnfmy.cnfmy.cnf.fallbackYou’ll also see the following directories:
conf.dmariadb.conf.dThe configuration file that MariaDB reads on startup is the /etc/mysql/mariadb.cnf file. This is where you’ll begin perusing when you want to configure the daemon, but we’ll get to that soon. The /etc/mysql/debian-start file is actually a script that sets default values for MariaDB when it starts, such as setting some environment variables. It also defines a task that is executed if the mariadb process dies or exits, and allows it to check for crashed tables.
The debian-start script also loads the /etc/mysql/debian.cnf file, which sets some client settings for the mariadb daemon. Here’s a list of values from that file:
[client]host = localhostuser = root[mysql_upgrade]host = localhostuser = rootThe defaults for these values are fine and there’s rarely a reason to change them. Essentially, the file sets the default user, host, and socket location. If you’ve used MySQL before on other platforms, you may have seen many of those settings in the /etc/my.cnf file, which is typically the standard file for the mariadb daemon. With MariaDB on Ubuntu Server, you can see that the default layout of the files was changed considerably.
The /etc/mysql/mariadb.cnf file sets the global defaults for MariaDB. However, in Ubuntu’s implementation, this default file just includes configuration files from the /etc/mysql/conf.d and /etc/mysql/mariadb.conf.d directories. Within those directories, there are additional files ending with the .cnf extension. Many of these files contain default configuration values that would normally be found in a single file, but Ubuntu’s implementation modularizes these settings into separate files instead. For our purposes in this book, we’ll be editing the /etc/mysql/conf.d/mysql.cnf file when it is time to set up a relationship between primary and secondary servers.
The other configuration files aren’t relevant for the content of this book, and their current values are more than sufficient for what we need. When it comes to performance tuning, you may consider creating a new configuration file ending with the .cnf extension, with specific tuning values as provided by the documentation of a software package you want to run that interfaces with a database, or requirements given to you by a developer.
For additional information on how these configuration files are read, you can refer to the /etc/mysql/mariadb.cnf file, which includes some helpful content at the top of the file that details the order in which these configuration files are read, as well as their purpose. Here’s an excerpt of these comments from that file:
# The MariaDB/MySQL tools read configuration files in the following order:# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,# 2. "/etc/mysql/conf.d/*.cnf" to set global options.# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.# 4. "~/.my.cnf" to set user-specific options.As we can see, when MariaDB starts up, it first reads the /etc/mysql/mariadb.cnf file, followed by .cnf files stored within the /etc/mysql/conf.d directory, then the .cnf files stored within the /etc/mysql/mariadb.conf.d directory, followed by any user-specific settings stored within a .my.cnf file that may be present in the user’s home directory.
With Ubuntu’s implementation, when the /etc/mysql/mariadb.cnf file is read during startup, the process will immediately scan the contents of /etc/mysql/conf.d and /etc/mysql/mariadb.conf.d, because the /etc/mysql/mariadb.cnf file contains the following lines:
!includedir /etc/mysql/conf.d/!includedir /etc/mysql/mariadb.conf.d/As you can see, the order that the configuration files are checked is set to the mariadb.cnf file first, followed by the /etc/mysql/conf.d and /etc/mysql/mariadb.conf.d directories.
This may be a bit confusing at first, because the default configuration for MariaDB in Ubuntu Server essentially consists of files that redirect to other files. But the main takeaway is that any configuration changes you make that are not exclusive to MariaDB (basically, configuration that’s compatible with MySQL itself) should be placed in a configuration file that ends with the .cnf extension, and then stored in the /etc/mysql/conf.d directory.
If the configuration you’re wanting to add is for a feature exclusive to MariaDB (but not compatible with MySQL itself), the configuration file should be placed in the /etc/mysql/mariadb.conf.d directory instead. For our purposes, we’ll be editing the /etc/mysql/conf.d/mysql.cnf file when it comes time to set up our primary/secondary replication, since the method we’ll be using is not specific to MariaDB.
In this section, we discussed MariaDB configuration and how it differs from its implementation in other platforms. The way the configuration files are presented is not the only difference in Ubuntu’s implementation of MariaDB; there are other differences as well. In the next section, we’ll take a look at a few additional ways in which Ubuntu’s implementation differs from implementations in other distributions of Linux.
Managing MariaDB databases
Section titled “Managing MariaDB databases”Now that our MariaDB server is up and running, we can finally look into managing it. In this section, I’ll demonstrate how to connect to a database server using the mariadb command, which will allow us to create databases, remove (drop) them, and also manage users and permissions.
To begin, we’ll need to create an administrative user for MariaDB. The root account already exists as the default administrative user, but it’s not a good idea to allow others to use that account. Instead, it makes more sense to create an administrative account separate from root for managing our databases. Therefore, we’ll begin our discussion on managing databases with user management. The users we’ll manage within MariaDB are specific to MariaDB; these are separate from the user accounts on the actual system.
To manage and interact with databases, we’ll need to enter the MariaDB shell, and the same goes for when it comes to creating database users. Right now, since we only have the root account, we’ll need to access the current MariaDB implementation as root in order to set up our administrative user. If you’ve set up standard authentication, as we discussed earlier in this chapter, you can access the prompt using the standard means:
mariadb -u root -pOr, more simply:
sudo mariadbOnce inside the MariaDB shell, your prompt will change to the following:
MariaDB [(none)]>Now, we can create our new administrative user. I’ll call mine admin in my examples, but you can use whatever name you’d like. In a company I used to work for, we used the username velociraptor as our administrative user on our servers, since nothing is more powerful than a velociraptor (and they can open doors). Feel free to use a clever name, but just make sure you remember it. Using a non-standard username has the added benefit of security by obscurity; the name wouldn’t be what an intruder would expect.
Here’s the command to create a new user in MariaDB (replace the username and password in the command with your desired credentials):
CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password';FLUSH PRIVILEGES;When it comes to MySQL syntax, the commands are not case sensitive (though the data parameters are), but it’s common to capitalize instructions to separate them from data. During the remainder of this chapter, we’ll be executing some commands within the Linux shell, and others within the MariaDB shell. I’ll let you know which shell each command needs to be executed in as we come to them, but if you are confused, just keep in mind that MariaDB commands are the only ones that are capitalized.
With the preceding commands, we’re creating the admin user and restricting it to localhost. This is important because we don’t want to open up the admin account to the world. We’re also flushing privileges, which causes MariaDB to reload its privileges information. The FLUSH PRIVILEGES command should be run every time you add a user or modify permissions. I may not always mention the need to run this command, so you might want to make a mental note of it and make it a habit now.
As I mentioned, the previous command created the admin user but is only allowing it to connect from localhost. This means that an administrator would first need to log in to the server itself before they would be able to log in to MariaDB with the admin account. As an example of the same command (but allowing remote login from any other location), the following command is a variation that will do just that:
CREATE USER 'admin'@'%' IDENTIFIED BY 'password';Can you see the percent symbol (%) in place of localhost? That basically means everywhere, which indicates we’re creating a user that can be logged into from any source (even external nodes). However, by restricting our user to localhost with the first command, we’re making our server just a bit more secure. You can also restrict access to particular networks, which is desired if you really do need to allow a database administrator access to the server remotely:
CREATE USER 'admin'@'192.168.1.%' IDENTIFIED BY 'password';That’s a little better, but not as secure as limiting login to localhost. As you can see, the % character is basically a wildcard, so you can restrict access to needing to be from a specific IP or even a particular subnet.
So far, all we did is create a new user; we have yet to give this user any permissions. We can create a set of permissions (also known as grants) with the GRANT command. First, let’s give our admin user full access to the database server when called from localhost:
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost';FLUSH PRIVILEGES;Now, we have an administrative user we can use to manage our server’s databases. We can use this account for managing our server instead of the root account. Any logged-on Linux user will be able to access the database server and manage it, provided they know the password. To access the MariaDB shell as the admin user that we created, the following command will do the trick:
mariadb -u admin -pAfter entering the password, you’ll be logged into MariaDB as admin.
In addition, you can actually provide the password to the mariadb command without needing to be prompted for it:
mariadb -u admin -p<password>Notice that there is no space in between the -p option and the actual password (though it’s common to put a space between the -u option and the username). As useful as it is to provide the username and password in one shot, I don’t recommend that you ever use that method. This is because any Linux command you type is saved in the history, so anyone can view your command history and they’ll see the password in plain text. I only mention it here because I find that many administrators do this, even though they shouldn’t. At least now you’re aware of this method and why it’s wrong.
The admin account we created is only intended for system administrators who need to manage databases on the server. The password for this account should not be given to anyone other than staff employees or administrators that absolutely need it. Additional users can be added to the MariaDB server, each with differing levels of access. Keep in mind that our admin account can manage databases but not users. This is important, as you probably shouldn’t allow anyone other than server administrators to create users. You’ll still need to log in as root to manage user permissions.
It may also be useful to create a read-only user for MariaDB for employees who need to be able to read data but not make changes. Back in the MariaDB shell (as root), we can issue the following command to effectively create a read-only user:
GRANT SELECT ON *.* TO 'readonlyuser'@'localhost' IDENTIFIED BY 'password';With this command (and flushing privileges afterward), we’ve done two things. First, we’ve created a new user and also set up grants for that user with a single command. Second, we’ve created a read-only user that can view databases but not manage them (we’ve restricted the permissions to SELECT). This is more secure. In practice, it’s better to restrict a read-only user to a specific database. This is typical in a development environment, where you’ll have an application that connects to a database over a network and needs to read information from it. We’ll go over this scenario soon.
Next, let’s create a database. At the MariaDB prompt, execute:
CREATE DATABASE mysampledb;That was easy. We should now have a database on our server named mysampledb. To list all databases on our server (and confirm our database was created properly), we can execute the following command:
SHOW DATABASES;This will produce an output like the following:

Figure 13.1: Listing MariaDB databases
The output will show some system databases that were created for us, but our new database should be listed among them. We can also list users just as easily:
SELECT HOST, USER, PASSWORD FROM mysql.user;Entering this command will result in something similar to the following output:

Text Description automatically generated
Figure 13.2: Listing MariaDB users
In a typical scenario, when installing an application that needs its own database, we’ll create the database and then a user for that database. We’ll normally want to give that user permission to only that database, with only as much permission as required to allow it to function properly. We’ve already created the mysampledb database, so if we want to create a user with read-only access to it, we can do so with the following command:
GRANT SELECT ON mysampledb.* TO 'appuser'@'localhost' IDENTIFIED BY 'password';With one command, we’re not only creating the user appuser, but we’re also setting a password for it, in addition to allowing it to have SELECT permissions on the mysampledb database. This is equivalent to read-only access. If our user needed full access, we could use the following instead:
GRANT ALL ON mysampledb.* TO 'appuser'@'localhost' IDENTIFIED BY 'password';To double-check that we’ve executed the command correctly, we can use this command to show the grants for a particular user:
SHOW GRANTS FOR 'appuser'@'localhost';Now, our appuser has full access but only to the mysampledb database. Of course, we should only provide full access to the database if absolutely necessary. We can also provide additional permissions, such as DELETE (whether or not the user has permission to delete rows from database tables), CREATE (which controls whether the user can add rows to the database), INSERT (controls whether or not the user can add new rows to a table), SELECT (allows the user to read information from the database), DROP (allows the user to fully remove a database), and ALL (which gives the user everything). There are other permissions we can grant or deny; check the MariaDB documentation for more details. The types of permissions you’ll need to grant to a user to satisfy the application you’re installing will depend on the documentation for that software. Always refer to the installation instructions for the application you’re attempting to install to determine which permissions are required for it to run.
If you’d like to remove user access, you can use the following command to do so (substituting myuser with the user account you wish to remove):
DROP USER 'myuser'@'localhost'Now, let’s go back to databases. Now that we’ve created the mysampledb database, what can we do with it? We’ll add tables and rows, of course! A database is useless without actual data, so we can work through some examples of adding data to our database to see how this works. First, log in to the MariaDB shell as a user with full privileges to the mysampledb database. Now, we can have some fun and modify the contents. Here are some examples you can follow:
USE mysampledb;The USE command allows us to select a database we want to work with. The MariaDB prompt will change from MariaDB [(none)]> to MariaDB [mysampledb]>. This is very useful, as the MariaDB prompt changes to indicate which database we are currently working with. We basically just told MariaDB that for all of the commands we’re about to execute, we would like them to be issued against the mysampledb database.
Now, we can CREATE a table in our database. It doesn’t matter what you call yours, since we’re just practicing. I’ll call mine Employees:
CREATE TABLE Employees (Name char(15), Age int(3), Occupation char(15));We can verify this command by showing the columns in the database, to ensure it shows what we expect:
SHOW COLUMNS IN Employees;With this command, we’ve created a table named Employees that has three columns (Name, Age, and Occupation). To add new data to this table, we can use the following INSERT command:
INSERT INTO Employees VALUES ('Joe Smith', '26', 'Ninja');The example INSERT command adds a new employee to our Employees table. When we use INSERT, we insert all the data for each of the columns. Here, we have an employee named Joe, who is 26 years old and whose occupation is a Ninja. Feel free to add additional employees; all you would need to do is formulate additional INSERT statements and provide data for each of the three fields. When you’re done, you can use the following command to show all of the data in this table:
SELECT * FROM Employees;
Figure 13.3: Listing database rows from a table
To remove an entry, the following command will do what we need:
DELETE FROM Employees WHERE Name = 'Joe Smith';Basically, we’re using the DELETE FROM command, giving the name of the table we wish to delete from (Employees, in this case), and then using WHERE to provide some search criteria for narrowing down our command.
The DROP command allows us to delete tables or entire databases, and it should be used with care. I don’t actually recommend you delete the database we just created, since we’ll use it for additional examples. But if you really wanted to drop the Employees table, you could use:
DROP TABLE Employees;Or use this to drop the entire database:
DROP DATABASE mysampledb;There is, of course, much more to MariaDB and its MySQL syntax than the samples I have provided, but this should be enough to get you through the examples in this book. As much as I would love to give you a full walkthrough of the MySQL syntax, it would easily push this chapter beyond a reasonable number of pages. If you’d like to push your skills beyond the samples of this chapter, there are great books available that are dedicated to the subject.
Before I close this section though, I think it will be worthwhile for you to see how to back up and restore your databases. To do this, we have the mysqldump command at our disposal. Its syntax is very simple, as you’ll see.
First, exit the MariaDB shell and return to your standard Linux shell. Since we’ve already created an admin user earlier in the chapter, we’ll use that user for the purposes of our backup:
mysqldump -u admin -p --databases mysampledb > mysampledb.sqlWith this example, we’re using mysqldump to create a copy of the mysampledb database and storing it in a file named mysampledb.sql. Since MariaDB requires us to log in, we authenticate to MariaDB using the -u option with the username admin and the -p option, which will prompt us for a password. The --databases option is necessary because, by default, mysqldump does not include the database create statement. However, the --databases option forces this, which just makes it easier for you to restore. Assuming that we were able to authenticate properly, the contents of the mysampledb database will be dumped into the mysampledb.sql file. This export should happen very quickly, since this database probably only contains a single table and a few rows. Larger production databases can take hours to dump.
Restoring a backup is fairly simple. We can utilize the mariadb command with the backup file used as a source of input:
sudo mariadb -u admin -p < mysampledb.sqlSo, there you have it. The mysqldump command is definitely very handy in backing up databases. In the next section, we’ll work through setting up a secondary database server.
Setting up a secondary database server
Section titled “Setting up a secondary database server”Redundancy is an amazing thing. If a primary server fails for some reason, you can keep your applications running by having a secondary database server available in case the original meets its demise. Of course, you can always create regular backups of your database servers and restore if necessary, but it’s very hard to keep up with databases that are always changing, so backups have a tendency to become stale quite fast. A secondary database server enables you to have a copy that is always up to date. This doesn’t mean that you no longer need backups, but it does give you another option for recovery when faced with a problem.
The industry is moving away from terms like “Master” and “Slave” to describe a primary and secondary server. In this chapter and moving forward, we will use the terms “Primary” and “Secondary” to describe the relationship of one main database server that replicates to another. Therefore, the verbiage around our actions will use “primary” and “secondary,” even though the verbiage inside Ubuntu 22.04 still uses the old terminology. Just keep in mind that the naming will likely switch to a new naming scheme in the future.
At this point, we have one database server already. To set up a secondary database instance, all you really need in order to begin the process is to set up another physical server or virtual machine and install the mariadb-server package as we did earlier. If you’ve already set up two database servers as recommended earlier in the chapter, you’re ready to begin. If not, feel free to spin up another virtual machine and follow the process from the Installing MariaDB section, which covered the initial setup of MariaDB. Go ahead and set up another server if you haven’t already done so. Of your two servers, one should be designated as the primary and the other as the secondary, so make a note of the IP addresses for each.
To begin, we’ll first start working on the primary. We’ll need to edit the /etc/mysql/conf.d/mysql.cnf file on the server you wish to be the primary. Currently, the file contains just the following line:
[mysql]Right underneath that, add a blank line and then the following code:
[mysqld]log-binbinlog-do-db=mysampledbserver-id=1With this configuration, we’re first enabling binary logging, which is required for a primary/secondary server to function properly. Binary logs contain records of all database changes, which enables a secondary database instance to reproduce changes made to the primary server. These binary logs record changes made to a database, which will then be transferred to a secondary server.
Another configuration file that we’ll need to edit is /etc/mysql/mariadb.conf.d/50-server.cnf. In this file, we have the following line:
bind-address = 127.0.0.1With this default setting, the mysql daemon is only listening for connections on localhost (127.0.0.1), which is a problem since we’ll need to connect to it from another machine (the secondary server). Change this line to the following:
bind-address = 0.0.0.0Next, we’ll need to access the MariaDB shell on the primary server and execute the following commands:
GRANT REPLICATION SLAVE ON *.* to 'replicate'@'192.168.1.204' identified by 'password';Here, we’re creating a replication user named replicate and allowing it to connect to our primary server from the IP address 192.168.1.204. Be sure to change that IP to match the IP of your secondary server, but you can also use a hostname identifier such as %.mydomain if you have a domain configured, which is equivalent to allowing any hostname that ends with .mydomain. Also, we’re setting the password for this user to password, so feel free to customize that as well to fit your password requirements (be sure to make a note of the password).
We should now restart the mariadb daemon so that the changes we’ve made to the mysql.cnf file take effect:
sudo systemctl restart mariadbNext, we’ll set up the secondary server. But before we do that, there’s a consideration to make now that will possibly make the process easier on us. In a production environment, it’s very possible that data is still being written to the primary server. The process of setting up a secondary server is much easier if we don’t have to worry about the primary database changing while we set up the secondary. The following command, when executed within the MariaDB shell, will lock the database and prevent additional changes:
FLUSH TABLES WITH READ LOCK;If you’re absolutely sure that no data is going to be written to the primary server, you can disregard that step.
Next, we should utilize mysqldump to make sure that both the primary and the secondary servers contain the same data before we start synchronizing them. The process is smoother if we begin with them already synchronized, rather than trying to mirror the databases later. Using mysqldump as we did in the previous section, create a dump of the primary server’s database and then import that dump into the secondary. The easiest way to transfer the dump file is to use rsync or scp. Then, on the secondary instance, use mariadb to import the file.
The command to back up the database on the primary server becomes the following:
mysqldump -u admin -p --databases mysampledb > mysampledb.sqlAfter transferring the mysampledb.sql file to the secondary server, you can import the backup into the secondary server:
mariadb -u root -p < mysampledb.sqlAlso on the secondary server, we’ll need to edit /etc/mysql/conf.d/mysql.cnf and then place the following code at the end (make sure to add a blank line after [mysql]:
[mysqld]server-id=2Although it’s outside the scope of this book, you can set up more than just one secondary database server. If you do, each will need a unique server-id.
Make sure you restart the mariadb unit on the secondary server before continuing:
sudo systemctl restart mariadbFrom the root MariaDB shell on your secondary server, enter the following command. Change the IP address in the command accordingly:
CHANGE MASTER TO MASTER_HOST="192.168.1.184", MASTER_USER='replicate', MASTER_PASSWORD='password';Now that we’re finished configuring the synchronization, we can unlock the primary server’s tables. On the primary server, execute the following command within the MariaDB shell:
UNLOCK TABLES;Now, we can check the status of the secondary server to see whether or not it is running.
Within the secondary server’s MariaDB shell, execute the following command:
SHOW SLAVE STATUS \G;Here, we’re adding \G, which changes the output to be displayed vertically instead of horizontally.
Assuming all went well, we should see the following line in the output:
Slave_IO_State: Waiting for master to send eventIf the secondary server isn’t running (Slave_IO_State is blank), execute the following command:
START SLAVE;Next, check the status of the secondary server process again to verify:
SHOW SLAVE STATUS \G;From this point forward, any data you add to your database on the primary server should be replicated to the secondary. To test, add a new record to the Employees table on the mysampledb database on the primary server:
USE mysampledb;INSERT INTO Employees VALUES ('Optimus Prime', '100', 'Transformer');On the secondary server, check the same database and table for the new value to appear. It may take a second or two:
USE mysampledb;SELECT * FROM Employees;If you see any errors in the Slave_IO_State line when you run SHOW SLAVE STATUS \G, or your databases aren’t synchronizing properly, here are a few things you can try. First, make sure that the primary database server is listening for connections on 0.0.0.0 port 3306.
To test this, run this variation of the ss command to see which port the mariadb process is listening on (it’s listed as mysqld):
ss -tulpn | grep mysqldThe output should be similar to the following:
tcp LISTEN 0 80 0.0.0.0:3306 0.0.0.0:* users:(("mysqld",pid=9768,fd=23))If you see that the service is listening on 127.0.0.1:3306 instead, that means it’s only accepting connections from localhost. Earlier in this section, I mentioned changing the bind address in the /etc/mysql/mariadb.conf.d/50-server.cnf file. Make sure you’ve already done that and restart mariadb. During my tests, I’ve actually had one situation where the mariadb service became locked after I made this change, and attempting to restart the process did nothing (I ended up having to reboot the entire server, which is not typically something you’d have to do). Once the server came back up, it was listening for connections from the network.
If you receive errors on the secondary server when you run SHOW SLAVE STATUS \G, with regards to authentication, make sure you’ve run FLUSH PRIVILEGES on the primary server. Even if you have, run it again to be sure. Also, double-check that you’re synchronizing with the correct username, IP address, and password. For your convenience, here’s the command we ran on the primary server to grant replication permissions:
GRANT REPLICATION SLAVE ON *.* to 'replicate'@'192.168.1.204' identified by 'password';FLUSH PRIVILEGESHere’s the command that we ran on the secondary server:
CHANGE MASTER TO MASTER_HOST="192.168.1.184", MASTER_USER='replicate', MASTER_PASSWORD='password';Finally, make sure that your primary database and the secondary database both contain the same databases and tables. The primary server won’t be able to update a database on the secondary server if it doesn’t exist there. Flip back to my example usage on mysqldump if you need a refresher. You should only need to use mysqldump and import the database onto the secondary server once, since after you get the replication going, any changes made to the database on the primary server should follow over to the secondary. If you have any difficulties with the mysqldump command, you can manually create mysampledb and the Employees table on the secondary server, which is really all it needs for synchronization to start.
Synchronization should then begin within a minute, but you can execute STOP SLAVE, followed by START SLAVE, on the secondary server to force it to try to synchronize again without waiting.
And that should be all there is to it. At this point, you should have fully functional primary and secondary database servers at your disposal. To get additional practice, try adding additional databases, tables, and users, and insert new rows into your databases.
It’s worth mentioning that the users we’ve created here will not be synced to the secondary server, so you can use the commands we used earlier in this chapter to create users on the secondary server if you wish for them to be present there.
Summary
Section titled “Summary”Depending on your skill set, you’re either an administrator who is learning about SQL databases for the first time, or you’re a seasoned veteran who is curious about how to implement a database server with Ubuntu Server. In this chapter, we dove into Ubuntu’s implementation of this technology and worked through setting up our own database server. We also worked through some examples of the MariaDB syntax, such as creating databases, as well as setting up users and their grants. We also worked through setting up primary and secondary servers for replication.
Database administration is a vast topic, and we’ve only scratched the surface here. Being able to manage MySQL and MariaDB databases is a very sought-after skill for sure. If you haven’t worked with these databases before, this chapter will serve as a good foundation for you to start your research.
In the next chapter, we’ll use our database server to act as a foundation for Nextcloud, which we will set up as part of our look into setting up a web server. When you’ve finished practicing these database concepts, head on over to Chapter 14, Serving Web Content, where we’ll journey into the world of web hosting.
Further reading
Section titled “Further reading”- Configuring MariaDB with Option Files: https://mariadb.com/kb/en/configuring-mariadb-with-option-files/