Tutorial

How to Install MySQL on Ubuntu – Step-by-Step Guide

Updated on April 8, 2025
English
How to Install MySQL on Ubuntu – Step-by-Step Guide
Not using Ubuntu 20.04?Choose a different version or distribution.
Ubuntu 20.04

Introduction

MySQL is an open-source database management system, commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack. It implements the relational model and uses Structured Query Language (better known as SQL) to manage its data.

This tutorial will go over how to install MySQL version 8.0 on an Ubuntu 20.04 server. By completing it, you will have a working relational database that you can use to build your next website or application.

Create a MySQL database quickly using DigitalOcean Managed Databases. Let DigitalOcean focus on maintaining, upgrading, and backups.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Installing MySQL

On Ubuntu, you can install MySQL using the APT package repository. At the time of this writing, the version of MySQL available in the default Ubuntu repository is version 8.0.27.

To install it, update the package index on your server if you’ve not done so recently:

  1. sudo apt update

Then install the mysql-server package:

  1. sudo apt install mysql-server

Ensure that the server is running using the systemctl start command:

  1. sudo systemctl start mysql.service

These commands will install and start MySQL, but will not prompt you to set a password or make any other configuration changes. Because this leaves your installation of MySQL insecure, we will address this next.

Step 2 — Configuring MySQL

For fresh installations of MySQL, you’ll want to run the DBMS’s included security script. This script changes some of the less secure default options for things like remote root logins and sample users.

Warning: As of July 2022, an error will occur when you run the mysql_secure_installation script without some further configuration. The reason is that this script will attempt to set a password for the installation’s root MySQL account but, by default on Ubuntu installations, this account is not configured to connect using a password.

Prior to July 2022, this script would silently fail after attempting to set the root account password and continue on with the rest of the prompts. However, as of this writing the script will return the following error after you enter and confirm a password:

Output
... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters. New password:

This will lead the script into a recursive loop which you can only get out of by closing your terminal window.

Because the mysql_secure_installation script performs a number of other actions that are useful for keeping your MySQL installation secure, it’s still recommended that you run it before you begin using MySQL to manage your data. To avoid entering this recursive loop, though, you’ll need to first adjust how your root MySQL user authenticates.

First, open up the MySQL prompt:

  1. sudo mysql

Then run the following ALTER USER command to change the root user’s authentication method to one that uses a password. The following example changes the authentication method to mysql_native_password:

  1. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

After making this change, exit the MySQL prompt:

  1. exit

Following that, you can run the mysql_secure_installation script without issue.

Once the security script completes, you can then reopen MySQL and change the root user’s authentication method back to the default, auth_socket. To authenticate as the root MySQL user using a password, run this command:

  1. mysql -u root -p

Then go back to using the default authentication method using this command:

  1. ALTER USER 'root'@'localhost' IDENTIFIED WITH auth_socket;

This will mean that you can once again connect to MySQL as your root user using the sudo mysql command.

Run the security script with sudo:

  1. sudo mysql_secure_installation

This will take you through a series of prompts where you can make some changes to your MySQL installation’s security options. The first prompt will ask whether you’d like to set up the Validate Password Plugin, which can be used to test the password strength of new MySQL users before deeming them valid.

If you elect to set up the Validate Password Plugin, any MySQL user you create that authenticates with a password will be required to have a password that satisfies the policy you select. The strongest policy level — which you can select by entering 2 — will require passwords to be at least eight characters long and include a mix of uppercase, lowercase, numeric, and special characters:

Output
Securing the MySQL server deployment. Connecting to MySQL using a blank password. VALIDATE PASSWORD COMPONENT can be used to test passwords and improve security. It checks the strength of password and allows the users to set only those passwords which are secure enough. Would you like to setup VALIDATE PASSWORD component? Press y|Y for Yes, any other key for No: Y There are three levels of password validation policy: LOW Length >= 8 MEDIUM Length >= 8, numeric, mixed case, and special characters STRONG Length >= 8, numeric, mixed case, special characters and dictionary file Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2

Regardless of whether you choose to set up the Validate Password Plugin, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice:

Output
Please set the password for root here. New password: Re-enter new password:

Note that even though you’ve set a password for the root MySQL user, this user is not currently configured to authenticate with a password when connecting to the MySQL shell.

If you used the Validate Password Plugin, you’ll receive feedback on the strength of your new password. Then the script will ask if you want to continue with the password you just entered or if you want to enter a new one. Assuming you’re satisfied with the strength of the password you just entered, enter Y to continue the script:

Output
Estimated strength of the password: 100 Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y

From there, you can press Y and then ENTER to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.

Once the script completes, your MySQL installation will be secured. You can now move on to creating a dedicated database user with the MySQL client.

Step 3 — Creating a Dedicated MySQL User and Granting Privileges

Upon installation, MySQL creates a root user account which you can use to manage your database. This user has full privileges over the MySQL server, meaning it has complete control over every database, table, user, and so on. Because of this, it’s best to avoid using this account outside of administrative functions. This step outlines how to use the root MySQL user to create a new user account and grant it privileges.

In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This plugin requires that the name of the operating system user that invokes the MySQL client matches the name of the MySQL user specified in the command, so you must invoke mysql with sudo privileges to gain access to the root MySQL user:

  1. sudo mysql

Note: If you installed MySQL with another tutorial and enabled password authentication for root, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:

  1. mysql -u root -p

Once you have access to the MySQL prompt, you can create a new user with a CREATE USER statement. These follow this general syntax:

  1. CREATE USER 'username'@'host' IDENTIFIED WITH authentication_plugin BY 'password';

After CREATE USER, you specify a username. This is immediately followed by an @ sign and then the hostname from which this user will connect. If you only plan to access this user locally from your Ubuntu server, you can specify localhost. Wrapping both the username and host in single quotes isn’t always necessary, but doing so can help to prevent errors.

You have several options when it comes to choosing your user’s authentication plugin. The auth_socket plugin mentioned previously can be convenient, as it provides strong security without requiring valid users to enter a password to access the database. But it also prevents remote connections, which can complicate things when external programs need to interact with MySQL.

As an alternative, you can leave out the WITH authentication_plugin portion of the syntax entirely to have the user authenticate with MySQL’s default plugin, caching_sha2_password. The MySQL documentation recommends this plugin for users who want to log in with a password due to its strong security features.

Run the following command to create a user that authenticates with caching_sha2_password. Be sure to change sammy to your preferred username and password to a strong password of your choosing:

  1. CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';

Note: There is a known issue with some versions of PHP that causes problems with caching_sha2_password. If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, mysql_native_password plugin instead:

  1. CREATE USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

If you aren’t sure, you can always create a user that authenticates with caching_sha2_plugin and then ALTER it later on with this command:

  1. ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows:

  1. GRANT PRIVILEGE ON database.table TO 'username'@'host';

The PRIVILEGE value in this example syntax defines what actions the user is allowed to perform on the specified database and table. You can grant multiple privileges to the same user in one command by separating each with a comma. You can also grant a user privileges globally by entering asterisks (*) in place of the database and table names. In SQL, asterisks are special characters used to represent “all” databases or tables.

To illustrate, the following command grants a user global privileges to CREATE, ALTER, and DROP databases, tables, and users, as well as the power to INSERT, UPDATE, and DELETE data from any table on the server. It also grants the user the ability to query data with SELECT, create foreign keys with the REFERENCES keyword, and perform FLUSH operations with the RELOAD privilege. However, you should only grant users the permissions they need, so feel free to adjust your own user’s privileges as necessary.

You can find the full list of available privileges in the official MySQL documentation.

Run this GRANT statement, replacing sammy with your own MySQL user’s name, to grant these privileges to your user:

  1. GRANT CREATE, ALTER, DROP, INSERT, UPDATE, INDEX, DELETE, SELECT, REFERENCES, RELOAD on *.* TO 'sammy'@'localhost' WITH GRANT OPTION;

Note that this statement also includes WITH GRANT OPTION. This will allow your MySQL user to grant any permissions that it has to other users on the system.

Warning: Some users may want to grant their MySQL user the ALL PRIVILEGES privilege, which will provide them with broad superuser privileges akin to the root user’s privileges, like so:

  1. GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;

Such broad privileges should not be granted lightly, as anyone with access to this MySQL user will have complete control over every database on the server.

Following this, it’s good practice to run the FLUSH PRIVILEGES command. This will free up any memory that the server cached as a result of the preceding CREATE USER and GRANT statements:

  1. FLUSH PRIVILEGES;

Then you can exit the MySQL client:

  1. exit

In the future, to log in as your new MySQL user, you’d use a command like the following:

  1. mysql -u sammy -p

The -p flag will cause the MySQL client to prompt you for your MySQL user’s password in order to authenticate.

Finally, let’s test the MySQL installation.

Step 4 — Testing MySQL

Regardless of how you installed it, MySQL should have started running automatically. To test this, check its status.

  1. systemctl status mysql.service

You’ll see output similar to the following:

Output
● mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2020-04-21 12:56:48 UTC; 6min ago Main PID: 10382 (mysqld) Status: "Server is operational" Tasks: 39 (limit: 1137) Memory: 370.0M CGroup: /system.slice/mysql.service └─10382 /usr/sbin/mysqld

If MySQL isn’t running, you can start it with sudo systemctl start mysql.

For an additional check, you can try connecting to the database using the mysqladmin tool, which is a client that lets you run administrative commands. For example, this command says to connect as a MySQL user named sammy (-u sammy), prompt for a password (-p), and return the version. Be sure to change sammy to the name of your dedicated MySQL user, and enter that user’s password when prompted:

  1. sudo mysqladmin -p -u sammy version

You should see output similar to this:

Output
mysqladmin Ver 8.0.19-0ubuntu5 for Linux on x86_64 ((Ubuntu)) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Server version 8.0.19-0ubuntu5 Protocol version 10 Connection Localhost via UNIX socket UNIX socket /var/run/mysqld/mysqld.sock Uptime: 10 min 44 sec Threads: 2 Questions: 25 Slow queries: 0 Opens: 149 Flush tables: 3 Open tables: 69 Queries per second avg: 0.038

This means MySQL is up and running.

MySQL vs MariaDB installation on Ubuntu

MySQL and MariaDB are two of the most popular open-source relational database management systems (RDBMS) used for storing and managing structured data. Both are widely used in web applications and are known for their high performance, scalability, and reliability.

Here’s a comparison of MySQL and MariaDB installations on Ubuntu:

Feature MySQL MariaDB
License GPL GPL
Storage Engines InnoDB, MyISAM, Memory, etc. InnoDB, Aria, TokuDB, etc.
Performance Optimized for high-performance and scalability Enhanced performance with better query optimization
Security Strong focus on security with features like SSL/TLS encryption Enhanced security features, including better password hashing and encryption
Replication Supports Master-Slave and Master-Master replication Supports Master-Slave and Master-Master replication with improved performance
Fork Oracle-owned, with a more commercial focus Community-driven fork of MySQL, with a focus on open-source
Default Storage Engine InnoDB, known for its transactional capabilities Aria, designed for high-performance and reliability
Default Charset utf8mb4, supporting a wide range of languages utf8mb4, ensuring compatibility with a variety of languages
SQL Syntax Supports a wide range of SQL syntax and features Compatible with MySQL SQL syntax, with additional features and improvements
Community Support Large community and extensive documentation Active community with a focus on open-source collaboration and development
Compatibility Compatible with a wide range of platforms and tools Compatible with MySQL tools and platforms, with additional support for open-source technologies

Common Errors and Debugging

MySQL Service Not Starting

If the MySQL service fails to start, you can try the following steps to troubleshoot and resolve the issue:

  1. Check the MySQL error log: For any errors or warnings that might indicate the cause of the problem. You can do this by running the command sudo grep 'error' /var/log/mysql/error.log in your terminal.
  2. Ensure correct MySQL configuration: Ensure that the MySQL configuration file is correctly set up and that there are no syntax errors. You can check the configuration file by running sudo cat /etc/mysql/my.cnf and verify that it matches the expected format.
  3. Check for port conflicts: Check if the MySQL service is already running under a different user or if there are any other processes using the same port. You can do this by running sudo netstat -tlnp | grep 3306 to check if any process is using the default MySQL port.
  4. Manually start the MySQL service: Try starting the MySQL service manually using the command sudo service mysql start or sudo systemctl start mysql.

Authentication Plugin Errors

Authentication plugin errors can occur due to compatibility issues between the MySQL client and server versions. To resolve this issue:

  1. Verify version compatibility: Ensure that the MySQL client and server versions are compatible. You can check the MySQL server version by running sudo mysql -V and the client version by running mysql -V.
  2. Check authentication plugin configuration: Check if the authentication plugin is correctly configured on the server. You can do this by running SELECT @@default_authentication_plugin; in your MySQL client.
  3. Update or change authentication plugin: Try using a different authentication plugin or updating the MySQL client to a compatible version. For example, you can update the MySQL client by running sudo apt update && sudo apt install mysql-client.

MySQL Installation Failed: Missing Dependencies

If the MySQL installation fails due to missing dependencies, you can try the following steps to resolve the issue:

  1. Check installation logs: Check the installation logs for any error messages indicating which dependencies are missing. You can do this by running sudo apt update && sudo apt install mysql-server and checking the output for any error messages.
  2. Install missing dependencies: Use the package manager to install the missing dependencies. For example, if the error message indicates that libssl1.1 is missing, you can install it by running sudo apt install libssl1.1.
  3. Retry MySQL installation: Once the dependencies are installed, retry the MySQL installation process by running sudo apt update && sudo apt install mysql-server.
  4. Ensure package manager is up to date: Ensure that the package manager is up to date and that all packages are correctly installed. You can do this by running sudo apt update && sudo apt full-upgrade.

System requirements for MySQL installation

Before installing MySQL, ensure your system meets the following requirements:

  • Operating System: Ubuntu 18.04 or later (64-bit)
  • CPU: 2 GHz dual-core processor
  • Memory: 4 GB RAM (8 GB or more recommended)
  • Storage: 2 GB free disk space (more recommended for larger databases)
  • Software: Ubuntu Server or Ubuntu Desktop with a compatible Linux kernel

Installing MySQL with Docker on Ubuntu

To install MySQL using Docker on Ubuntu, follow these steps:

  1. Install Docker: sudo apt update && sudo apt install docker.io
  2. Pull the MySQL image: sudo docker pull mysql
  3. Run the MySQL container: sudo docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password mysql
  4. Verify the installation: sudo docker exec -it mysql mysql -uroot -ppassword

Performance tuning MySQL after installation

After installing MySQL, consider the following performance tuning steps:

  1. Optimize the MySQL configuration file: Adjust settings in /etc/mysql/my.cnf to optimize performance based on your system’s resources.
  2. Use a suitable storage engine: Choose the most appropriate storage engine for your database, such as MyISAM for transactional workloads.
  3. Index your tables: Create indexes on frequently queried columns to improve query performance.
  4. Regularly update statistics: Run ANALYZE TABLE to update table statistics and improve query optimization.
  5. Monitor performance: Use tools like mysqladmin or sysdig to monitor MySQL performance and identify bottlenecks.

FAQs

How to install SQL in Ubuntu terminal?

To install MySQL on Ubuntu, run the following command in your terminal:

sudo apt update && sudo apt install mysql-server

This will install the MySQL server on your Ubuntu system.

How to install MySQL Workbench in Ubuntu 20.04 using terminal?

To install MySQL Workbench on Ubuntu 20.04, run the following command in your terminal:

sudo apt update && sudo apt install mysql-workbench

This will install MySQL Workbench on your Ubuntu 20.04 system.

How to setup a MySQL database?

To setup a MySQL database, follow these steps:

  • First, ensure MySQL is installed and running on your system.

  • Open a terminal and connect to the MySQL server using the following command:

sudo mysql -u root -p
  • Enter the root password when prompted.

  • Once connected, create a new database using the following SQL command:

CREATE DATABASE mydatabase;
  • To use the newly created database, run the following SQL command:
USE mydatabase;
  • Now you can create tables and insert data into your database.

What is the default MySQL root password on Ubuntu?

By default, the MySQL root password is not set on Ubuntu. You will be prompted to set a password during the installation process.

How do I start and stop MySQL on Ubuntu?

To start MySQL on Ubuntu, run the following command in your terminal:

sudo service mysql start

To stop MySQL on Ubuntu, run the following command in your terminal:

sudo service mysql stop

Can I install multiple MySQL versions on Ubuntu?

Yes, you can install multiple MySQL versions on Ubuntu using Docker. For example, to install MySQL 5.7 and MySQL 8.0, you can run the following commands:

sudo docker run --name mysql57 -p 3307:3306 -e MYSQL_ROOT_PASSWORD=password mysql:5.7
sudo docker run --name mysql80 -p 3308:3306 -e MYSQL_ROOT_PASSWORD=password mysql:8.0

This will install and run MySQL 5.7 and MySQL 8.0 in separate containers.

How do I completely uninstall MySQL from Ubuntu?

To completely uninstall MySQL from Ubuntu, run the following command in your terminal:

sudo apt purge mysql-server mysql-client mysql-common
sudo apt autoremove
sudo apt autoclean

This will remove MySQL server, client, and common files from your system.

What’s the difference between MariaDB and MySQL on Ubuntu?

MariaDB is a fork of MySQL, and both are relational database management systems. MariaDB is designed to be a drop-in replacement for MySQL, offering improved performance and new features. On Ubuntu, you can install MariaDB instead of MySQL using the following command:

sudo apt update && sudo apt install mariadb-server

MariaDB is compatible with MySQL, and most MySQL applications can work with MariaDB without modification.

Conclusion

With your basic MySQL setup now installed on your server, you’re ready to take your database management to the next level. Here are a few examples of next steps you can take to further enhance your MySQL experience and learn more about it:

Want to launch a high-availability MySQL cluster in a few clicks? DigitalOcean offers worry-free MySQL managed database hosting. We’ll handle maintenance and updates and even help you migrate your database from external servers, cloud providers, or self-hosted solutions. Leave the complexity to us, so you can focus on building a great application.

Learn more here

About the author(s)

Hazel Virdó
Hazel Virdóstaff technical writer
See author profile
Mark Drake
Mark DrakeManager, Developer Education
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Hello,

How I can install MySQL 5? This is very important to me for using Magento 1 version.

Thank you.

I have this error at mysql_secure_installation :

Re-enter new password: … Failed! Error: Password hash should be a 41-digit hexadecimal number

For those who wonder why this isn’t working, it is because sudo apt install mysql-server install latest version of mysql, which is mysql 8 or latest. mysql 5.7 installation need to refers to other tutorial

hi

I followed your tutorial on ubuntu 16.4 and it seems to be working all fine, now I have another question, my software instruction asks: the table engine must be “MyISAM”. With new MySQL versionit’s always InnoDB. Set “default-storage-engine” option to “MyISAM” in “/etc/mysql/my.cnf”

can you guide me on how to do that?

Thanks

Hello Mark, Thanks for the share of this tutorial, it helped me a lot, First time I do this without any issues and very clear all your steps on this article. Appreciate it. Thank You.

On Ubuntu 20.04, fresh mysql installation. In step 3 when setting up a new user, Plugin 'authentication_plugin' is not loaded.

Great Article it worked for me

This will not work on a server with 512mb RAM. To fix, add some swap space.

But you can add some swap fairly easily. I used the instructions at this link, but there were some other good simple tutorials if this no longer works: https://salslab.com/a/running-mysql-on-a-vps-with-512mb-ram/

“sudo mysql_secure_installation” on a brand-new Ubuntu 20.04 provided by Digital Ocean gave the following error after attempting to set the root password:

“Failed! Error: SET PASSWORD has no significance for user ‘root’@‘localhost’ as the authentication method used doesn’t store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.”

So to workaround this, use CTRL-C to cancel the mysql_secure_installation script and do the following:

sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by '<rootpassword>';
quit

Then you can run “sudo mysql_secure_installation” again and this time, decline the option to change the root password so you can perform the other steps of the script.

Note that once this is set, you’ll access mysql with the password, like so, instead of just “sudo mysql”

mysql -u root -p

I recently ran into the issue of not being able to log in after Step 2- mysql_secure_installation in WSL2

sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
exit
sudo mysql_secure_installation 
# various prompts within this step

mysql -u root -p



mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (13)

What worked was using TCP connection to connect rather than a socket connection

mysql -u root -p --protocol=tcp

OR use sudo

sudo mysql -u root -p
[sudo] password for vivek:  <---- the sudo user password
Enter password: <---- mysql password

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.