Installing and Securing MySQL/MariaDB on Ubuntu

This guide walks you through the steps to install and secure MySQL or MariaDB on Ubuntu. You'll also learn how to set a root password and secure the installation to improve database security.

← Back

Step 1: Install MySQL or MariaDB

You can choose to install MySQL or the open-source compatible MariaDB:

Option 1: Install MySQL

sudo apt install mysql-server

Option 2: Install MariaDB

sudo apt install mariadb-server

Step 2: Secure the Installation

Once installed, run the included security script to remove insecure defaults and improve your database security:

sudo mysql_secure_installation

You will be prompted to:

Choose yes for all prompts unless you have specific reasons to do otherwise.

Step 3: Set or Change the Root Password (If Skipped)

If you skipped setting the root password during the mysql_secure_installation process, or wish to change it later, follow these steps:

Log into MySQL as Root:

sudo mysql

Set the Password (MySQL 5.7+ / MariaDB 10.4+):

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password'; FLUSH PRIVILEGES; EXIT;

Make sure to replace your_password with a strong, secure password of your choice.

Step 4: Test the Login

Verify that you can now log in with your root password:

mysql -u root -p

It will prompt you for your password and grant access to the MySQL shell if everything is correct.

← Back