In this guide, you’ll learn how to install and configure MySQL on a Linux system. If you already have a previous version of MySQL installed, you will need to clean it up before proceeding.

Clean Up Existing MySQL Installation Link to heading

  • Remove MySQL and Related Packages

    sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-*
    sudo apt-get autoremove
    sudo apt-get autoclean
    
  • Set Up MySQL Directories and Permissions

    sudo mkdir -p /var/lib/mysql
    sudo mkdir -p /var/run/mysqld
    sudo chown -R mysql:mysql /var/lib/mysql
    sudo chown -R mysql:mysql /var/run/mysqld
    sudo chmod 750 /var/run/mysqld
    

Install MySQL Link to heading

  1. Update Package Lists and Install MySQL

    sudo apt-get update
    sudo apt-get install mysql-server
    
  2. Initialize MySQL

    sudo mysqld --initialize --user=mysql --datadir=/var/lib/mysql
    
  3. Start MySQL Service

    sudo systemctl start mysql
    
  4. Check MySQL Status and Logs

    Verify that MySQL is running:

    sudo systemctl status mysql
    
  5. Secure the Installation

    sudo mysql_secure_installation
    
  6. Log In with the Temporary Password

    Use the temporary password generated during installation:

    sudo mysql -u root -p
    
Note
The temporary password will be shown during the installation. If you missed it, you can find it in the logs:
  • Viewing MySQL error logs

    sudo less /var/log/mysql/error.log
    

Look for a line that’s similar to: A temporary password is generated for root@localhost: TEMP_PASSWORD

Resetting the Root Password Link to heading

If you stll can’t find the temporary password, or if you need to reset it, follow these steps:

  • Stop the MySQL Service

    sudo systemctl stop mysql
    
  • Start MySQL in Safe Mode

    sudo mysqld_safe --skip-grant-tables &
    
  • Create the MySQL Run Directory (if necessary)

    If /var/run/mysqld doesn’t exist, create it:

    sudo mkdir -p /var/run/mysqld
    sudo chown mysql:mysql /var/run/mysqld
    
  • Log Into MySQL Without a Password

    mysql -u root 
    
  • Reset the Root Password

    Execute the following commands in the MySQL prompt:

    FLUSH PRIVILEGES;
    ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOUR_NEW_PASSWORD'; -- Replace YOUR_NEW_PASSWORD with your new password
    EXIT;
    
  • Stop MySQL Safe Mode

    sudo killall mysqld_safe
    
  • Restart MySQL

    sudo systemctl start mysql
    
  • Log In with the New Password

    mysql -u root -p
    

References Link to heading

Install MySQL on Ubuntu

Ubuntu Server