Beginner’s Guide to Installing and Configuring MariaDB on Ubuntu

目次

1. Introduction

MariaDB is an open-source relational database management system (RDBMS) that originated as a fork of MySQL. In recent years, MariaDB has been widely adopted in projects that leverage databases, and its performance and reliability have earned the support of many companies and developers.

Features and Benefits of MariaDB

MariaDB’s biggest strength is that it maintains high compatibility with MySQL while evolving independently. Below are the main advantages of MariaDB.
  • Open-source license: MariaDB is developed under the GPL (GNU General Public License) and is available for free.
  • High compatibility: When migrating data and applications from MySQL to MariaDB, no major modifications are required.
  • Enhanced security: MariaDB comes with strengthened security settings by default, allowing you to build a highly secure environment.
  • Scalability: It is optimized to handle large datasets and high‑load systems.

Benefits of Using MariaDB on Ubuntu

Ubuntu is a Linux distribution widely used in server environments. Using MariaDB on Ubuntu provides the following benefits.
  1. Stability: Ubuntu’s LTS (Long‑Term Support) releases guarantee stability and long‑term security updates.
  2. Ease of package management: Using the apt command makes installing and updating MariaDB straightforward.
  3. Broad support: Because the Ubuntu‑MariaDB combination is popular among developers, you can easily find troubleshooting information in online documentation and forums.

Article Goal

In this article, we will walk through installing MariaDB on an Ubuntu environment, covering basic configuration, usage, and troubleshooting in detail. The guide aims to help readers of all skill levels—from beginners to intermediate users—effectively leverage MariaDB.

2. Prerequisites

Before installing MariaDB on Ubuntu, preparing the necessary prerequisites helps you proceed smoothly. This section explains the recommended environment, dependency packages, and how to update the repository in detail.

Recommended Environment

To run MariaDB efficiently, we recommend the following environment.
  • Ubuntu version:
  • We recommend using a supported LTS version (such as 20.04, 22.04, etc.).
  • Hardware requirements:
  • Memory: at least 512 MB (2 GB or more recommended)
  • Disk space: at least 500 MB free (more may be needed depending on data size)
  • CPU: processor of 1 GHz or higher (multiple cores recommended)
Meeting these requirements allows you to operate MariaDB stably.

Dependency Packages and System Requirements

Installing MariaDB requires several dependency packages. Run the following commands to check dependencies in advance and install the required packages.
sudo apt update
sudo apt install -y software-properties-common gnupg
This enables you to add repositories and manage GPG keys. Also, if you plan to use curl or wget, installing them is convenient.
sudo apt install -y curl wget

Updating the Repository

To obtain the latest package information, first update the system’s repository. Run the following commands.
sudo apt update
sudo apt upgrade -y
  • apt update: Retrieves the latest package list from the current repository.
  • apt upgrade: Updates installed packages on the system to their latest versions.

Verifying SSH Connection (for Remote Servers)

If you are installing MariaDB on a remote server, make sure the SSH connection is stable beforehand. You can verify the connection as follows.
ssh username@server_ip_address
To avoid configuration errors in a remote environment, be careful not to lose the connection during the installation.

3. Installing MariaDB

To install MariaDB on Ubuntu, you can use either the default repository or the official repository. Below, we’ll walk through each method in detail.

Installing from the Default Repository

The MariaDB version in Ubuntu’s default repository prioritizes stability. Install it using the steps below.

Steps

  1. Update the repository.
   sudo apt update
  1. Install MariaDB.
   sudo apt install -y mariadb-server mariadb-client
  1. After installation, check the status of the MariaDB service.
   sudo systemctl status mariadb
  1. If the MariaDB service doesn’t start automatically, start it manually with the following command.
   sudo systemctl start mariadb
  1. Configure the service to start automatically.
   sudo systemctl enable mariadb

Advantages

  • Using the default repository makes it easier to receive official Ubuntu support.
  • Installation is straightforward with simple steps.

Installing Using the Official Repository

If you want the latest MariaDB version, use the official repository. This method gives you access to newer features and performance improvements.

Steps

  1. Add the official MariaDB repository.
   sudo apt install -y software-properties-common
   sudo add-apt-repository 'deb [arch=amd64,arm64,ppc64el] http://mirror.aarnet.edu.au/pub/mariadb/repo/10.6/ubuntu focal main'
  1. Add the repository’s GPG key.
   sudo apt-key adv --fetch-keys 'https://mariadb.org/mariadb_release_signing_key.asc'
  1. Update the package list.
   sudo apt update
  1. Install MariaDB.
   sudo apt install -y mariadb-server mariadb-client
  1. Check the service status and start it.
   sudo systemctl status mariadb
   sudo systemctl start mariadb
   sudo systemctl enable mariadb

Cautions

  • When using the official repository, it may conflict with Ubuntu’s default repository. If you encounter errors during installation, remove any conflicting packages.

Post-Installation Verification

Once MariaDB is installed, verify it with the following commands.

Check Version

mysql --version

Connect to MariaDB

sudo mysql
If you can connect to the MariaDB console successfully, the installation was successful.

4. Initial Setup and Security Hardening

After installing MariaDB, you need to harden security and perform basic configuration. This section details the initial setup and recommended security hardening steps.

Running mysql_secure_installation

Immediately after installing MariaDB, the default settings leave it vulnerable. Run the following command to apply basic security settings.

Executing the Command

sudo mysql_secure_installation

Explanation of Each Prompt

  1. Enter current root password
  • If this is the first time, no password is set, so press Enter.
  1. Set root password
  • Choose a strong password. For example: at least 12 characters, mixing letters, numbers, and symbols.
  1. Remove anonymous users
  • Recommended: Y (delete anonymous users)
  1. Disable remote root login
  • Recommended: Y (disable remote login for root user)
  1. Remove test database
  • Recommended: Y (delete the unnecessary default database)
  1. Reload privilege tables
  • Recommended: Y (apply changes immediately)
This completes the basic security configuration.

Configuring Authentication Plugins

By default, MariaDB uses the unix_socket plugin to authenticate the root user. While convenient, it can cause issues when connecting from other tools or scripts. Switch the authentication method as needed.

Check Current Authentication Method

sudo mysql -e "SELECT user, host, plugin FROM mysql.user;"

Changing Authentication Method (e.g., to mysql_native_password)

  1. Connect to the MariaDB console.
   sudo mysql
  1. Change the plugin.
   ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'new_password';
   FLUSH PRIVILEGES;
  1. Verify the changes.
   SELECT user, host, plugin FROM mysql.user;

Character Set Configuration

Setting the database character set correctly prevents garbled text and data inconsistencies. Using utf8mb4 is generally recommended.

How to Configure

  1. Edit the configuration file.
   sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
  1. Add or modify the following lines.
   [mysqld]
   character-set-server=utf8mb4
   collation-server=utf8mb4_general_ci
  1. Restart MariaDB.
   sudo systemctl restart mariadb
  1. Verify the configuration.
   SHOW VARIABLES LIKE 'character_set%';

Setting a Password Policy

We recommend configuring a password policy to maintain strong security.

Configuration Steps

  1. Enable the validate_password plugin.
   sudo mysql -e "INSTALL PLUGIN validate_password SONAME 'validate_password.so';"
  1. Check or modify the password policy.
   SHOW VARIABLES LIKE 'validate_password%';
   SET GLOBAL validate_password.length = 12;
   SET GLOBAL validate_password.mixed_case_count = 1;
   SET GLOBAL validate_password.number_count = 1;
   SET GLOBAL validate_password.special_char_count = 1;

5. Basic Operations

After installing MariaDB and completing the initial setup and security hardening, let’s learn the basic operation methods. This section covers managing the MariaDB service, creating databases, configuring users, and backup and restoration.

Managing the MariaDB Service

Below are the basic commands for operating the MariaDB service.

Starting the Service

To start the MariaDB service, run the following command.
sudo systemctl start mariadb

Stopping the Service

To stop the service, use the following command.
sudo systemctl stop mariadb

Restarting the Service

If you need to restart MariaDB after changing settings, execute the following.
sudo systemctl restart mariadb

Checking the Service Status

To verify that MariaDB is running correctly, run the following command.
sudo systemctl status mariadb

Creating a Database

To create a database, connect to the MariaDB console.

Connecting to the Console

Connect to MariaDB with the following command.
sudo mysql

Creating a Database

Use the CREATE DATABASE command to create a new database.
CREATE DATABASE sample_db;

Verifying the Created Database

You can list the databases with the following command.
SHOW DATABASES;

Creating Users and Setting Permissions

In MariaDB, you can create new users and grant them permissions on specific databases.

Creating a User

Create a new user with the following command.
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password123';

Granting Permissions

Grant the created user all privileges on a specific database.
GRANT ALL PRIVILEGES ON sample_db.* TO 'new_user'@'localhost';
After granting permissions, you need to reload the privileges.
FLUSH PRIVILEGES;

Verifying Users and Permissions

To check the current users and permissions, use the following commands.
SELECT user, host FROM mysql.user;
SHOW GRANTS FOR 'new_user'@'localhost';

Backup and Restoration

In MariaDB, performing regular backups is essential to protect your data.

Creating a Backup

Use the mysqldump command to back up the database.
mysqldump -u root -p sample_db > sample_db_backup.sql

Restoring a Backup

Restore the database using a backup file.
mysql -u root -p sample_db < sample_db_backup.sql

6. Troubleshooting

MariaDB can encounter errors and issues during installation, configuration, or operation. This section explains common problems and their solutions.

When MariaDB Won’t Start

Symptoms

Attempting to start MariaDB results in an error and the service fails to start.

Solution

  1. Check Service Status
   sudo systemctl status mariadb
If the status shows “failed”, check the error message.
  1. Check Error Log MariaDB’s error log is stored at the following location.
   sudo cat /var/log/mysql/error.log
Examine the log to identify the specific error.
  1. Check Disk Space MariaDB uses disk space for log files and data storage. Insufficient free space can prevent the service from starting.
   df -h
Delete unnecessary files as needed to free up space.
  1. Modify Configuration File If there is a configuration error, check MariaDB’s config file (/etc/mysql/mariadb.conf.d/50-server.cnf).
  2. Restart Service After fixing the issue, restart MariaDB.
   sudo systemctl restart mariadb

When Permission Errors Occur

Symptoms

When a specific user tries to access the database, an “Access denied for user” error is displayed.

Solution

  1. Check User Privileges Connect to MariaDB and verify the user’s privileges.
   SHOW GRANTS FOR 'username'@'hostname';
  1. Grant Appropriate Privileges Grant the necessary privileges.
   GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'hostname';
   FLUSH PRIVILEGES;
  1. Verify Hostname Configuration Ensure the host the user is connecting from (e.g., localhost or %) is correct.

Database Connection Errors

Symptoms

Unable to connect to MariaDB from a client application.

Solution

  1. Check If MariaDB Allows Remote Connections By default, MariaDB only allows connections from localhost. To permit remote connections, modify the bind-address.
   sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
Check or modify the following line.
   bind-address = 0.0.0.0
  1. Firewall Settings Ensure the port MariaDB uses (default: 3306) is open.
   sudo ufw allow 3306
   sudo ufw reload
  1. Configure User for Remote Connections Create or configure a user that is allowed to connect from remote hosts.
   CREATE USER 'username'@'%' IDENTIFIED BY 'password';
   GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'%';
   FLUSH PRIVILEGES;

Performance Issues

Symptoms

MariaDB queries are slow, or the server experiences high load.

Solution

  1. Query Optimization
  • Enable the slow query log to identify slow queries. ini slow_query_log = 1 long_query_time = 2
  • Check the log: bash sudo cat /var/log/mysql/slow.log
  1. Add Indexes
  • Adding appropriate indexes to frequently used queries improves search speed. sql CREATE INDEX idx_column ON table_name(column_name);
  1. Use Caching Enable query cache in MariaDB’s configuration file.
   query_cache_size = 16M
   query_cache_type = 1
  1. Monitor Server Resources Use top or htop commands to check CPU and memory usage, and increase server resources as needed.

7. FAQ (Frequently Asked Questions)

Here we have compiled common questions and answers for using MariaDB on Ubuntu. These Q&As provide useful information for users ranging from beginners to intermediate level.

Q1: What is the difference between MariaDB and MySQL?

MariaDB is an open-source relational database management system (RDBMS) that originated from MySQL. Below are the main differences:
  • License: MariaDB uses the GPL (GNU General Public License) and adheres more strictly to open-source principles than MySQL.
  • Features: MariaDB introduces new features faster than MySQL, with enhanced query optimization and plugins.
  • Development model: MySQL is led by Oracle, whereas MariaDB is developed by an independent community.

Q2: How do I install a specific version of MariaDB?

You can install a specific version by using MariaDB’s official repository. Below is an example procedure (installing version 10.6):
  1. Add the official MariaDB repository:
   sudo add-apt-repository 'deb [arch=amd64,arm64,ppc64el] http://mirror.aarnet.edu.au/pub/mariadb/repo/10.6/ubuntu focal main'
  1. Update the package list and install:
   sudo apt update
   sudo apt install -y mariadb-server

Q3: I don’t understand the settings of mysql_secure_installation.

mysql_secure_installation is a script that simplifies security configuration for MariaDB. The main settings are explained below:
  • Setting the root password: It is not set by default, so be sure to assign a strong password.
  • Removing anonymous users: Deleting anonymous users is recommended to improve security.
  • Removing the test database: Delete the test database that comes with MariaDB.
  • Reloading privilege tables: Apply configuration changes immediately.

Q4: Why set the character set to utf8mb4?

utf8mb4 is a full implementation of UTF-8 that supports all characters, including emojis and special symbols. Setting it helps prevent garbled text and data loss. Example configuration:
[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci

Q5: How can I improve MariaDB performance?

Consider the following to boost MariaDB performance:
  • Query optimization: Enable the slow query log to identify poorly performing queries.
  • Utilizing indexes: Create indexes on columns that are frequently used.
  • Cache configuration: Properly set up the query cache in MariaDB’s configuration file to store reusable results.
  • Resource monitoring: Monitor CPU and memory usage to reduce server load.

Q6: Is there a way to automate MariaDB backups?

Yes, you can automate backups using cron. Below is an example that runs a backup daily at 3 AM:
  1. Create a backup script:
   nano /usr/local/bin/backup_mariadb.sh
Contents:
   #!/bin/bash
   mysqldump -u root -p'password' --all-databases > /backup/mariadb_backup_$(date +%F).sql
  1. Make the script executable:
   chmod +x /usr/local/bin/backup_mariadb.sh
  1. Set up the cron job:
   crontab -e
Add the following line:
   0 3 * * * /usr/local/bin/backup_mariadb.sh

8. Summary and Next Steps

In this article, we detailed the steps to install MariaDB on Ubuntu and operate it safely and efficiently. Below is a brief recap of what was covered in each section.

Key Points of the Article

  1. Introduction
  • We explained the features of MariaDB and the benefits of using it on Ubuntu.
  1. Prerequisites
  • We reviewed the recommended environment, dependencies, and repository update procedures before installation.
  1. Installing MariaDB
  • We learned how to install using the default repository and the official MariaDB repository.
  1. Initial Configuration and Security Hardening
  • We covered security configuration with mysql_secure_installation, setting authentication plugins, and changing character sets.
  1. Basic Operations
  • We covered managing the service, creating databases, configuring users and privileges, and performing backups and restores.
  1. Troubleshooting
  • We examined solutions for startup errors, permission issues, connection problems, and performance concerns.
  1. FAQ (Frequently Asked Questions)
  • We provided detailed explanations of basic MariaDB concepts, useful configuration tips, and automating backups.

Next Steps

Once you’re comfortable with the basics of MariaDB, learning advanced features and configurations will enable you to build a more efficient and robust database environment.

Learn Replication

Using MariaDB replication helps ensure data redundancy and improve availability. We recommend learning how to set up master‑slave replication and multi‑master (master‑master) configurations.

Performance Tuning

As data volume and traffic grow, performance can become a challenge. Learn query optimization, index utilization, and server setting adjustments to get the most out of MariaDB.

Further Strengthening Security

  • Configure secure connections using SSL/TLS
  • Implement log monitoring and data encryption

Advanced MariaDB Features

  • High‑availability clustering with Galera Cluster
  • Leverage modern features such as the JSON data type and full‑text search

Reference Links

To continue deepening your knowledge, please use the following resources.