MySQL is an open-source relational database management system, commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack. It uses Structured Query Language (SQL) to manage data.
This tutorial covers installing MySQL on Ubuntu. By completing it, you’ll have a working relational database ready for your website or application.
Create a MySQL database quickly using DigitalOcean Managed Databases. Let DigitalOcean focus on maintaining, upgrading, and backups.
Quick installation: Install MySQL on Ubuntu with sudo apt install mysql-server. The default Ubuntu repository provides MySQL 8.x, compatible with Ubuntu 20.04, 22.04, and later versions. After installation, MySQL starts automatically and is ready for configuration.
Secure your installation: Run sudo mysql_secure_installation to remove insecure defaults, disable remote root access, and set up password validation policies. On Ubuntu, you may need to adjust the root authentication method first using ALTER USER to avoid the recursive loop issue that occurs with MySQL 8.0+ installations.
Create dedicated users: Avoid using the root account for daily operations. Create dedicated MySQL users with CREATE USER and grant only the necessary privileges using GRANT statements. This follows the principle of least privilege and improves database security.
Authentication plugins matter: Choose the right authentication plugin based on your use case. Use caching_sha2_password (MySQL 8.0 default) for modern applications, or mysql_native_password for compatibility with older PHP applications like phpMyAdmin.
Troubleshooting essentials: Common issues include service startup failures, authentication plugin mismatches, and port conflicts. Check logs with sudo grep -i 'error' /var/log/mysql/error.log, verify service status with sudo systemctl status mysql, and check port usage with sudo ss -tlnp | grep 3306.
To follow this tutorial, you will need:
On Ubuntu, you can install MySQL using the APT package repository. The default Ubuntu repository provides MySQL 8.x series. To check the exact version available, run apt-cache policy mysql-server after updating your package index. This guide is compatible with Ubuntu 20.04, 22.04, and later versions.
To install it, update the package index on your server if you’ve not done so recently:
- sudo apt update
Then install the mysql-server package:
- sudo apt install mysql-server
Ensure that the server is running using the systemctl start command:
- 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. On Ubuntu, the default root MySQL account typically authenticates using the auth_socket plugin. This means any operating system user with sudo privileges can access MySQL as root without a database password, which can be a security concern on multi-user systems. We will address this in the next step.
For fresh installations of MySQL, run the DBMS’s included security script. This script changes some of the less secure default options, such as disabling remote root logins and removing sample users.
Warning: On some MySQL 8.0+ installations on Ubuntu, running the mysql_secure_installation script without first adjusting the root authentication method can trigger an error loop.
Previously, this script would silently fail after attempting to set the root account password and continue on with the rest of the prompts. In this scenario, the script may return the following error after you enter and confirm a 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.
New password:
This will lead the script into a recursive loop that you can only exit 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:
- 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:
- ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_strong_password';
After making this change, exit the MySQL prompt:
- 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:
- mysql -u root -p
Then go back to using the default authentication method using this command:
- 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:
- 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:
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 confirm a secure password:
Please set the password for root here.
New password:
Re-enter new password:
Note: On Ubuntu, the root MySQL user defaults to auth_socket authentication, which means the password you set during mysql_secure_installation may not be used for authentication. The auth_socket plugin takes precedence and allows root access only when the operating system user matches the MySQL user (requiring sudo mysql).
If you want to use password authentication for the root user, you’ll need to change the authentication method as shown earlier in the warning section above. Otherwise, you can continue using sudo mysql to connect as root, which is secure on single-user systems.
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 enter a new one. If satisfied with the password strength, enter Y to continue:
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`
Press Y and then ENTER to accept the defaults for all subsequent questions. This removes anonymous users and the test database, disables remote root logins, and applies the changes immediately.
Once the script completes, your MySQL installation is secured. You can now create a dedicated database user.
Upon installation, MySQL creates a root user account with full privileges over the MySQL server, including complete control over every database, table, and user. Avoid using this account outside of administrative functions. This step shows how to use the root MySQL user to create a new user account and grant it privileges.
On Ubuntu, the root MySQL user authenticates using the auth_socket plugin by default rather than with a password. This plugin requires the operating system user name to match the MySQL user name, so you must invoke mysql with sudo privileges to access the root MySQL user:
- 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:
- mysql -u root -p
Once you have access to the MySQL prompt, create a new user with a CREATE USER statement. The general syntax is:
- CREATE USER 'username'@'host' IDENTIFIED WITH authentication_plugin BY 'password';
After CREATE USER, specify a username followed by an @ sign and the hostname from which this user will connect. For local access only, specify localhost. Wrapping the username and host in single quotes prevents SQL syntax errors.
You have several authentication plugin options. The auth_socket plugin provides strong security without requiring a password but prevents remote connections. As an alternative, omit the WITH authentication_plugin portion to use MySQL’s default plugin, caching_sha2_password. The MySQL documentation recommends this plugin for password-based authentication due to its strong security features.
Run the following command to create a user that authenticates with caching_sha2_password. Replace sammy with your preferred username and password with a strong password:
- CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'your_strong_password';
Note: Some PHP versions have compatibility issues with caching_sha2_password. If you plan to use this database with a PHP application (such as phpMyAdmin), create a user with the mysql_native_password plugin instead:
- CREATE USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_strong_password';
Alternatively, create the user with caching_sha2_password and alter it later:
- ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_strong_password';
After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows:
- GRANT PRIVILEGE ON database.table TO 'username'@'host';
The PRIVILEGE value defines what actions the user can perform on the specified database and table. Grant multiple privileges in one command by separating each with a comma. Grant privileges globally by using asterisks (*) in place of database and table names, which represent “all” databases or tables in SQL. Use global privileges (*.*) only when necessary, as they grant access to all databases on the server.
The following command grants a user global privileges to CREATE, ALTER, and DROP databases, tables, and users, as well as INSERT, UPDATE, and DELETE data from any table. It also grants SELECT for querying data, REFERENCES for creating foreign keys, and RELOAD for FLUSH operations. Only grant users the permissions they need; adjust 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 MySQL user’s name:
- GRANT CREATE, ALTER, DROP, INSERT, UPDATE, INDEX, DELETE, SELECT, REFERENCES, RELOAD on *.* TO 'sammy'@'localhost' WITH GRANT OPTION;
Note that this statement includes WITH GRANT OPTION, which allows your MySQL user to grant any permissions 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:
- 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.
Run the FLUSH PRIVILEGES command to apply the changes:
- FLUSH PRIVILEGES;
Then you can exit the MySQL client:
- exit
To log in as your new MySQL user, use:
- mysql -u sammy -p
The -p flag prompts for your MySQL user’s password.
Finally, test MySQL to verify the installation.
MySQL should start automatically after installation. Check its status:
- sudo systemctl status mysql.service
You’ll see output similar to the following:
● 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, start it with sudo systemctl start mysql. Common reasons MySQL might not be running include: the service was stopped manually, system reboot without auto-start enabled, or configuration errors preventing startup.
For an additional check, connect to the database using the mysqladmin tool. This command connects as a MySQL user (-u sammy), prompts for a password (-p), and returns the version. Replace sammy with your dedicated MySQL user’s name:
- sudo mysqladmin -u sammy -p version
You should see output similar to this:
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 confirms MySQL is running.
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 | InnoDB, providing transactional support and compatibility with MySQL |
| 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 |
If the MySQL service fails to start, you can try the following steps to troubleshoot and resolve the issue:
sudo grep -i 'error' /var/log/mysql/error.log to identify errors or warnings (the -i flag makes the search case-insensitive).sudo cat /etc/mysql/my.cnf and the server-specific config with sudo cat /etc/mysql/mysql.conf.d/mysqld.cnf to ensure they’re correctly set up with no syntax errors.sudo ss -tlnp | grep 3306 to check if any process is using the default MySQL port (3306). The ss command is the modern replacement for netstat.sudo systemctl start mysql or sudo service mysql start.Authentication plugin errors can occur due to compatibility issues between the MySQL client and server versions. To resolve this issue:
sudo mysql -V and client version with mysql -V to ensure compatibility.SELECT @@default_authentication_plugin; in your MySQL client to verify the authentication plugin configuration.sudo apt update && sudo apt install mysql-client.If the MySQL installation fails due to missing dependencies, you can try the following steps to resolve the issue:
sudo apt update && sudo apt install mysql-server and check the output for error messages indicating missing dependencies.libssl3 instead of older versions. Run sudo apt install <package-name> where <package-name> is the specific dependency mentioned in the error.sudo apt update && sudo apt install mysql-server.sudo apt update && sudo apt full-upgrade to ensure the package manager and all packages are up to date.Before installing MySQL, ensure your system meets the following requirements:
To install MySQL using Docker on Ubuntu, follow these steps:
Install Docker: sudo apt update && sudo apt install docker.io
Pull the MySQL image: sudo docker pull mysql
Run the MySQL container: sudo docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=your_secure_password mysql:8.0
Security Warning: Replace your_secure_password with a strong password. Never use password or other weak passwords in production environments.
Verify the installation: sudo docker exec -it mysql mysql -uroot -p (you’ll be prompted for the password)
After installing MySQL, consider the following performance tuning steps:
/etc/mysql/my.cnf to optimize performance based on your system’s resources.ANALYZE TABLE to update table statistics and improve query optimization.mysqladmin for basic monitoring, or free tools like htop, iostat, and MySQL’s built-in Performance Schema to monitor MySQL performance and identify bottlenecks.To install MySQL Workbench on Ubuntu, run:
sudo apt update && sudo apt install mysql-workbench
This installs MySQL Workbench, a graphical tool for managing MySQL databases, on your Ubuntu system.
To start MySQL, run:
sudo systemctl start mysql
To stop MySQL, run:
sudo systemctl stop mysql
To check the service status, use sudo systemctl status mysql. For more details on service management and troubleshooting, see Step 4 — Testing MySQL.
Yes, you can run multiple MySQL versions simultaneously using Docker. Each container runs on a different port to avoid conflicts. For example:
sudo docker run --name mysql57 -p 3307:3306 -e MYSQL_ROOT_PASSWORD=your_secure_password mysql:5.7
sudo docker run --name mysql80 -p 3308:3306 -e MYSQL_ROOT_PASSWORD=your_secure_password mysql:8.0
Security Warning: Replace your_secure_password with a strong, unique password for each container. Never use password or other weak passwords.
This installs and runs MySQL 5.7 and MySQL 8.0 in separate containers. For more details on Docker installation, see Installing MySQL with Docker on Ubuntu.
To completely uninstall MySQL from Ubuntu, run:
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.
MariaDB is a fork of MySQL and both are relational database management systems. MariaDB is designed as a drop-in replacement for MySQL, offering improved performance and new features. On Ubuntu, install MariaDB instead of MySQL with:
sudo apt update && sudo apt install mariadb-server
MariaDB is compatible with MySQL, and most MySQL applications work with MariaDB without modification.
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:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Former Technical Writer at DigitalOcean. Focused on SysAdmin topics including Debian 11, Ubuntu 22.04, Ubuntu 20.04, Databases, SQL and PostgreSQL.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
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.
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.