How to Install MySQL 8.0 on Ubuntu Linux

MySQL 8.0 is a robust, reliable, high-performance relational database management system widely used for various applications, from web development to data warehousing. Known for its advanced features such as improved JSON support, window functions, and strong security enhancements, MySQL 8.0 is a top choice for developers and database administrators.

This guide demonstrates two ways to install MySQL 8.0 on Ubuntu using the terminal. You can either use the version available in Ubuntu’s default APT repositories or opt for the latest stable release from MySQL’s official APT repository, giving you flexibility between stability and newest features.

Refresh Ubuntu Packages Before MySQL 8.0 Installation

Updating your system before starting the installation is a best practice. This ensures all existing packages are up to date, minimizing the chance of conflicts during MySQL 8.0 installation.

Run the following commands to update and upgrade your system:

sudo apt update
sudo apt upgrade

Choose Your MySQL 8.0 Installation Method

MySQL 8.0 installation on Ubuntu offers two primary paths. Understanding the differences helps you select the method that aligns with your stability requirements and access to latest features.

Installation MethodVersion SourceStabilityBest For
Ubuntu RepositoryUbuntu’s curated packagesThoroughly tested and stableProduction systems, stability-focused environments
MySQL Official RepositoryMySQL Community ServerLatest upstream releasesDevelopment, systems needing latest features

Ubuntu’s default repository provides MySQL versions that have been integrated, tested, and optimized for Ubuntu releases. This approach is ideal for production servers where stability and long-term support matter more than bleeding-edge features. The official MySQL repository delivers the latest stable releases directly from MySQL’s development team, offering access to newest features, performance improvements, and security patches as soon as they’re available. Choose the Ubuntu repository for enterprise stability; select the official repository if your application requires specific MySQL 8.0 features or performance enhancements.

Option 1: Installing MySQL 8.0 with Ubuntu’s Repository

This is recommended if you seek a method that prioritizes system stability. Installing MySQL from Ubuntu’s default repository ensures a stable, thoroughly tested version of MySQL 8.0. Ubuntu’s package maintainers verify each release against the rest of the Ubuntu ecosystem, making this the safest choice for production servers and systems where uptime matters more than accessing the latest MySQL features immediately.

To install MySQL with this method, execute the following command:

sudo apt install mysql-server

The installation is non-interactive. MySQL installs, the service starts automatically, and Ubuntu’s package defaults to the auth_socket plugin for the root user instead of prompting for a password. After installation, run the security script in the “Secure MySQL 8.0” section to set a root password and tighten defaults.

Option 2: Install MySQL 8.0 with MySQL Community Server

This method suits those who want the most recent stable version of MySQL 8.0 directly from MySQL’s repository. MySQL 8.0 receives bug and security fixes through 2026, while MySQL 8.4 is the current LTS line with a longer lifecycle; pick 8.0 if you need compatibility with existing apps or replication pairs, and move to 8.4 for the longest support runway.

Install Repository Prerequisites

To ensure compatibility, install the required packages before proceeding:

sudo apt install gnupg dirmngr ca-certificates software-properties-common curl lsb-release -y

Add the MySQL APT Repository

To install MySQL from its official repository, import its GPG key and repository into your system. Here’s how you do it:

Import the GPG key (see the curl command guide if you want a refresher on the options used here):

curl -fsSL https://repo.mysql.com/RPM-GPG-KEY-mysql-2022 | sudo gpg --dearmor | sudo tee /usr/share/keyrings/mysql.gpg > /dev/null

Create a single DEB822 source file for MySQL 8.0 and the tools component:

cat <<EOF | sudo tee /etc/apt/sources.list.d/mysql.sources
Enabled: yes
Types: deb deb-src
URIs: https://repo.mysql.com/apt/ubuntu
Suites: $(lsb_release -cs)
Components: mysql-8.0 mysql-tools
Architectures: $(dpkg --print-architecture)
Signed-By: /usr/share/keyrings/mysql.gpg
EOF

Verify the file contents:

cat /etc/apt/sources.list.d/mysql.sources

Expected output (if all repositories added):

Enabled: yes
Types: deb deb-src
URIs: https://repo.mysql.com/apt/ubuntu
Suites: jammy
Components: mysql-8.0 mysql-tools
Architectures: amd64
Signed-By: /usr/share/keyrings/mysql.gpg

The Architectures field matches your system architecture (for example, amd64 or arm64), and Suites will reflect your Ubuntu codename (for example, jammy or noble). The mysql.gpg reference points to the key you imported earlier. If you see nothing, the repository file is empty and needs to be re-created; see the Troubleshooting section.

Refresh APT After Adding MySQL

Now that you’ve successfully imported the MySQL APT repository, it’s time to refresh the Advanced Package Tool (APT) cache to recognize the newly added repository.

Run the following command to update the APT cache:

sudo apt update

Install MySQL 8.0 Community Edition Server

With all the prerequisites, we are now ready to install MySQL 8.0 Community Edition Server. Run the following command to start the installation:

sudo apt install mysql-community-server

During installation, you’ll be prompted to set a password for the MySQL root user. Please ensure this password is secure and note it for future reference. After confirming the password, you’ll be asked to select the default authentication plugin. If in doubt, opt for the “Use Strong Password Encryption” recommended by MySQL.

To confirm the installation, check the installed MySQL version with the following command:

apt policy mysql-community-server

Example output:

mysql-community-server:
  Installed: 8.0.44-1ubuntu22.04
  Candidate: 8.0.44-1ubuntu22.04
  Version table:
 *** 8.0.44-1ubuntu22.04 500
        500 https://repo.mysql.com/apt/ubuntu jammy/mysql-8.0 amd64 Packages
        100 /var/lib/dpkg/status

This confirms MySQL 8.0 is installed. The version number (8.0.44 in this example) shows your installed MySQL build. The repository information (https://repo.mysql.com) confirms the package came from the official MySQL source. If you see “not installed” or the command returns nothing, the installation may have failed; see the Troubleshooting section below for solutions.

Service Commands for MySQL 8.0

With the MySQL 8.0 Community Edition Server installed, the system automatically activates the MySQL service and sets it to auto-start upon system boot. Understanding basic service management commands is essential for efficiently operating your database server.

After installation, one of the first tasks is to confirm that your MySQL service is running as expected. Using the systemctl command, specifically tailored for interacting with systemd services, you can view the current status of your MySQL service. Issue the following command:

systemctl status mysql

Successful output example:

mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2025-01-13 10:45:32 UTC; 2min 15s ago
   Main PID: 1234 (mysqld)
     Tasks: 28 (limit: 9405)
    Memory: 265.4M
       CPU: 1.234s
     CGroup: /system.slice/mysql.service
             |-1234 /usr/sbin/mysqld

Look for the line that says Active: active (running) to confirm MySQL is running properly. The “enabled” status means it will auto-start when you reboot. If you see inactive (dead), the service is stopped; use sudo systemctl start mysql to start it.

MySQL 8.0 Community Release systemctl status on Ubuntu Linux
MySQL 8.0 Community Release systemctl status on Ubuntu Linux

Understanding how to manage the MySQL service is critical to maintaining your database server. Various systemctl commands enable you to interact with the MySQL service directly. Here’s an overview of some essential commands:

Stopping the MySQL Service

To halt the MySQL service at any given time, use the following command:

sudo systemctl stop mysql

Starting the MySQL Service

If your MySQL service is not running, or after you’ve stopped it, start it with the following command:

sudo systemctl start mysql

Disabling the MySQL Service at System Startup

There might be situations where you’d prefer the MySQL service not to start automatically when your system boots. To disable auto-start, use the following command:

sudo systemctl disable mysql

Enabling the MySQL Service at System Startup

To revert the above action and set the MySQL service to start automatically upon system boot, use the following command:

sudo systemctl enable mysql

Restarting the MySQL Service

If you need to restart the MySQL service, for instance after making configuration changes, use the following command:

sudo systemctl restart mysql

Verify MySQL Connection After Installation

After installation completes, verify that MySQL is accepting connections. For Ubuntu’s repository packages, root uses the auth_socket plugin, so connect with:

sudo mysql

If you installed from the MySQL Community repository and set a root password, connect with:

mysql -u root -p

Upon successful authentication, you’ll see the MySQL prompt:

mysql>

This confirms MySQL is running and accepting connections. Type EXIT; to close the connection and return to the terminal.

Secure MySQL 8.0 on Ubuntu

Upon installing MySQL, certain default settings may not meet production security standards, potentially exposing your database to unauthorized access and attacks. MySQL provides a security hardening script, mysql_secure_installation, that helps secure your installation by removing unsafe defaults and enforcing security best practices.

Running the MySQL Security Script on Ubuntu

The mysql_secure_installation script is a part of the MySQL package that enhances security. Launch the script by issuing the following command. If you installed from Ubuntu’s repository and root uses the auth_socket plugin, the script may skip the root password prompt; it will ask for a password only if your installation already set one (such as the MySQL Community path).

sudo mysql_secure_installation

Interacting with the Security Script on Ubuntu

After running the command, the script prompts you to enter your root password when one exists. If you installed via Ubuntu’s repository and are still using auth_socket, connect with sudo mysql before running the script so the prompts succeed. You’ll encounter a prompt regarding the VALIDATE PASSWORD COMPONENT, which enforces password strength policies. The default settings are appropriate for most users. The script then walks you through five security hardening steps, each removing a default MySQL configuration that could pose security risks. Accepting all recommendations (answering “Y” to each prompt) follows security best practices for both development and production systems.

The script then takes you through a series of steps:

1. Password Settings for Root Accounts

Here, you have the chance to reset the root password. However, if you already set it during the initial installation, you may choose to skip this step. The script requires you to enter the new password twice for validation.

New password: <---- SET NEW PASSWORD
Re-enter new password: <---- RE-ENTER NEW PASSWORD

2. Removal of Anonymous Users

MySQL, by default, includes an anonymous user account. This account allows anyone to log into MySQL without having an authenticated user account, which can be a significant security risk. The script offers you the chance to remove these anonymous user accounts:

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y <---- Type Y then press the ENTER KEY.

3. Disallowing Root Login Remotely

In a standard security protocol, the root user should only be allowed to connect from ‘localhost’. This protocol ensures that remote attempts to guess the root password are mitigated. The script asks you to confirm the deactivation of remote root logins:

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y <---- Type Y then press the ENTER KEY.

4. Removal of Test Database

By default, MySQL installation includes a ‘test’ database. This database is accessible to anyone and is only meant for testing purposes. Before moving your setup to a production environment, it’s crucial to remove the test database and access it:

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y <---- Type Y then press the ENTER KEY.

5. Reloading Privilege Tables

Reloading the privilege tables allows all changes you’ve made so far to take effect immediately:

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y <---- Type Y then press the ENTER KEY.

By following these steps and confirming the security changes, you enhance the security of your MySQL server installation, mitigating the risk of potential exploits.

Managing MySQL 8.0

Managing your MySQL server involves several routine tasks such as updates, upgrades, and, when necessary, uninstallation. Ubuntu Linux provides efficient command-line utilities for these tasks, ensuring your MySQL server stays up-to-date and secure.

Update MySQL 8.0

Regular updates are essential to maintain the smooth running of your MySQL server. These updates often bring bug fixes, security patches, and new features, helping enhance your server’s overall security and functionality.

Whether you installed from Ubuntu’s repository or the MySQL APT repository, updating MySQL follows the normal APT workflow. The following command combines two distinct commands, sudo apt update, and sudo apt upgrade.

sudo apt update && sudo apt upgrade

The apt update command retrieves available package updates, while apt upgrade installs them to your system, including any available MySQL updates.

Remove MySQL 8.0

There might be instances when you no longer require the MySQL server on your Ubuntu system. The uninstallation process involves stopping MySQL service and removing the software and associated dependencies.

Stop the MySQL Service on Ubuntu

Before uninstallation, ensure that the MySQL service isn’t running. Use the following command to stop the service immediately:

sudo systemctl stop mysql

Remove MySQL and Its Dependencies

Now you can remove the MySQL server and its associated packages. Use the following command:

sudo apt autoremove mysql-community-server

Alternatively, use the following command if you used Ubuntu’s version:

sudo apt autoremove mysql-server

This command removes the MySQL server and cleans up unused packages or dependencies, freeing up system resources.

Remove MySQL 8.0 Repository

If you no longer intend to use MySQL and had previously imported the MySQL 8.0 Community Repository, removing the repository from your system is a good practice. Use the following commands to delete the MySQL source file and optional keyring, then refresh APT:

sudo rm /etc/apt/sources.list.d/mysql.sources
sudo rm /usr/share/keyrings/mysql.gpg  # optional if not reused
sudo apt update

This step ensures that your system won’t attempt to check the MySQL repository for updates during a system-wide upgrade, thus keeping your APT sources streamlined. If you also want to remove data files, delete or archive /var/lib/mysql after stopping the service.

Troubleshooting MySQL 8.0 Installation

Installation and configuration issues can occur due to system configuration, conflicting packages, or permission problems. This section covers common errors you might encounter and practical solutions.

MySQL Service Won’t Start After Installation

Symptom: systemctl status mysql shows inactive (dead) or displays error messages.

Solution: Check the MySQL error log to understand why the service failed:

sudo tail -50 /var/log/mysql/error.log

Common causes and fixes:

Port 3306 already in use: Another MySQL instance or service is using the default port.

sudo lsof -i :3306

If another process uses the port, either stop that process or configure MySQL to use a different port in /etc/mysql/mysql.conf.d/mysqld.cnf (change port = 3306 to port = 3307).

Permission denied on data directory: The MySQL user lacks write permissions to the data directory.

sudo chown -R mysql:mysql /var/lib/mysql
sudo chmod -R 750 /var/lib/mysql

After fixing permissions, attempt to start MySQL again:

sudo systemctl start mysql

Access Denied for User ‘root’ at Login

Symptom: mysql -u root -p returns “Access denied for user ‘root’@’localhost'”

Solution: First, check whether root uses socket authentication. On Ubuntu’s repository packages, root uses the auth_socket plugin, so connect with sudo mysql instead of a password. If you prefer a password, run the following SQL inside that session:

ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'your_new_password';
FLUSH PRIVILEGES;

For installations that already rely on a root password (such as the MySQL Community repository), reset it by starting MySQL in safe mode:

sudo systemctl stop mysql
sudo mysqld_safe --skip-grant-tables &
mysql -u root

Once connected, flush privileges and set a new password:

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';
EXIT;

Stop the safe mode instance and restart MySQL normally:

sudo pkill mysqld
sudo systemctl start mysql

Test the connection with your new password.

Socket Error: Can’t Connect to Local MySQL Server

Symptom: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Solution: This error indicates the MySQL service is not running or the socket file doesn’t exist. First, verify the service is running:

sudo systemctl status mysql

If the service is stopped, start it:

sudo systemctl start mysql

If the error persists after starting, check if the socket file exists:

ls -la /var/run/mysqld/mysqld.sock

If the file doesn’t exist, the data directory may be corrupted. Reinstall MySQL by removing it and reinstalling from scratch.

Repository Not Found During Installation

Symptom: E: Unable to locate package mysql-community-server when running sudo apt install mysql-community-server

Solution: The MySQL repository either wasn’t imported correctly or the APT cache wasn’t refreshed. Verify the repository file exists:

cat /etc/apt/sources.list.d/mysql.sources

If the file is empty or missing, re-import the repository using the commands in the “Option 2” section above. If you previously used a legacy mysql.list file, ensure it is removed to avoid duplicate entries. After re-importing, refresh the APT cache:

sudo apt update

Then attempt the installation again.

GPG Key Error During apt update

Symptom: GPG error: http://repo.mysql.com/apt/ubuntu ... NO_PUBKEY or similar when running sudo apt update

Solution: The MySQL GPG key wasn’t imported correctly. Re-import the key with the full command:

curl -fsSL https://repo.mysql.com/RPM-GPG-KEY-mysql-2022 | sudo gpg --dearmor | sudo tee /usr/share/keyrings/mysql.gpg > /dev/null
sudo apt update

If the error persists, verify the key was imported:

gpg --with-colons /usr/share/keyrings/mysql.gpg

You should see output showing the key details. If the file is empty or corrupted, delete it and re-import.

Installation Hangs or Prompts Unexpectedly

Symptom: sudo apt install mysql-community-server hangs without prompting for password or shows configuration dialogs that won’t respond.

Solution: Pre-set the MySQL root password before installation to avoid interactive prompts:

echo "mysql-community-server mysql-community-server/root-pass password YourPassword123" | sudo debconf-set-selections
echo "mysql-community-server mysql-community-server/re-root-pass password YourPassword123" | sudo debconf-set-selections
sudo DEBIAN_FRONTEND=noninteractive apt install -y mysql-community-server

Replace YourPassword123 with a strong password. The DEBIAN_FRONTEND=noninteractive flag prevents interactive prompts during installation.

MySQL Command Not Found

Symptom: mysql: command not found when attempting to connect.

Solution: The MySQL client may not be installed. Install the mysql-client package:

sudo apt install mysql-client

After installation, verify the client works:

mysql --version

Conclusion

MySQL 8.0 delivers a powerful, open-source relational database platform with robust security, advanced JSON support, and window functions. The installation process covers choosing between Ubuntu’s stable repository (for production systems prioritizing tested compatibility) and MySQL’s official repository (for access to the latest features and updates). Your Ubuntu server now runs a capable database platform ready for development, testing, or production deployment depending on your security and stability requirements.

Leave a Comment