How To Install MySQL on Ubuntu 22.04

How To Install MySQL on Ubuntu 22.04

Overview

A popular component of the LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack, MySQL is an open-source database management system. It manages its data using Structured Query Language, or SQL, and applies the relational model.

The installation of MySQL version 8.0 on an Ubuntu 20.04 server will be covered in this article. After finishing it, you’ll have a functional relational database that you may utilize to create your upcoming application or website.

Required conditions
In order to complete this tutorial, you’ll need:

One Ubuntu 22.04 server with a UFW-configured firewall and an administrative user who is not root. Follow our first Ubuntu 22.04 server setup instructions to get this configured.

Step 1 — Installing MySQL

On Ubuntu 20.04, 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:

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. 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:

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 '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 lead you through a series of prompts where you can adjust the security settings for your MySQL installation. The first prompt will ask if you want to activate the Validate Password Plugin, which may be used to verify a new MySQL user’s password strength before accepting it.

Any MySQL user you create that authenticates with a password will need to have a password that complies with the rules you choose if you choose to set up the Validate Password Plugin. Passwords for the strongest policy level, which you can choose by typing 2, must have a combination of uppercase, lowercase, numeric, and special characters and be at least eight characters long.

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:

The root MySQL user is not currently set up to authenticate with a password when connecting to the MySQL shell, despite the fact that you have provided a password for this user.

The strength of your new password will be evaluated if you utilized the Validate Password Plugin. After that, the script will prompt you to choose whether to keep using the password you just supplied or to enter a new one. Enter Y to carry on with the script, assuming you are happy with the strength of the password you just entered:

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

To accept the default answers for all further questions, press Y and then ENTER. This will load these new rules, deactivate remote root logins, remove a few anonymous users and the test database, and make MySQL obey your changes right now.

Your MySQL installation will be secured once the script runs. Using the MySQL client, you can now proceed to create a dedicated database user.

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:

sudo mysql

Note: To access the MySQL shell, you will need to use a different command if you installed MySQL using a different tutorial and configured password authentication for root. You can use your MySQL client with standard user credentials by doing the following; you can only access the database as an administrator by authenticating:

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:

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

You provide a username after CREATE USER. The @ symbol and the hostname, from which this user will connect, come right after this. You can set localhost if you only intend to use your Ubuntu server to access this user locally. Although it’s not always required, enclosing the host and username in single quotes can help to avoid mistakes.

When it comes to selecting the authentication plugin for your user, you have multiple choices. The previously stated auth_socket plugin might be useful since it offers robust protection without needing legitimate users to submit a password in order to access the database. However, it also blocks remote connections, which might cause issues when other programs need to communicate with MySQL.

Alternatively, you can have the user authenticate using MySQL’s default plugin, caching_sha2_password, by removing the WITH authentication_plugin part of the code completely. Because of its robust security features, the MySQL documentation suggests this plugin to users who wish to log in using a password.

To create a user that authenticates using caching_sha2_password, run the following command. Make sure Sammy has your desired username and that the password is a strong one that you have chosen:

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:

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:

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:

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

The activities that the user is permitted to take on the designated database and table are defined by the PRIVILEGE value in this example syntax. By using commas to separate each privilege, you can give the same user more than one in a single command. Asterisks (*) can be used in place of the database and table names to provide a user global privileges. Asterisks are special characters in SQL that are used to stand for “all” databases or tables.

For example, the following command gives a user the ability to INSERT, UPDATE, and DELETE data from any table on the server, as well as the ability to CREATE, ALTER, and DROP databases, tables, and users. Additionally, it gives the user access to the SELECT keyword for data querying, the REFERENCES keyword for creating foreign keys, and the RELOAD privilege for FLUSH operations. You can change your own user’s rights as needed, but you should only provide users the access they require.

The whole list of rights is accessible in the official MySQL manual.

Execute this GRANT statement and enter the name of your own MySQL user (sammy) to give your user these rights:

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:

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:

FLUSH PRIVILEGES;

Then you can exit the MySQL client:

exit

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

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.

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:

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.

Conclusion

Your server now has a simple MySQL installation installed on it. The following are some examples of actions you can perform next.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *