Tools: How to Install MySQL on Ubuntu – Step-by-Step Guide
Source: DigitalOcean
By Mark Drake, Anish Singh Walia and Vinayak Baranwal 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: Then install the mysql-server package: Ensure that the server is running using the systemctl start command: 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: 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: 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: After making this change, exit the MySQL prompt: 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: Then go back to using the default authentication method using this command: 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: 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: 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: 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: 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: 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: Once you have access to the MySQL prompt, create a new user with a CREATE USER statement. The general syntax is: 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: 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: Alternatively, create the user with caching_sha2_password and alter it later: After creating your new user, you can grant them the appropriate privileges. The general syntax for granting user privileges is as follows: 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: 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: 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: Then you can exit the MySQL client: To log in as your new MySQL user, use: 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: You’ll see output similar to the following: 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: You should see output similar to this: 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: If the MySQL service fails to start, you can try the following steps to troubleshoot and resolve the issue: Authentication plugin errors can occur due to compatibility issues between the MySQL client and server versions. To resolve this issue: If the MySQL installation fails due to missing dependencies, you can try the following steps to resolve the issue: 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: To install MySQL Workbench on Ubuntu, run: This installs MySQL Workbench, a graphical tool for managing MySQL databases, on your Ubuntu system. 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: 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: 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: 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. Learn more about our products 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! How I can install MySQL 5? This is very important to me for using Magento 1 version. 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 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? 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: 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” I recently ran into the issue of not being able to log in after Step 2- mysql_secure_installation in WSL2 What worked was using TCP connection to connect rather than a socket connection Please complete your information! 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.