Introduction
MySQL is one of the most popular open-source relational databases in the world. Whether you're running a web application, managing data, or building a backend system, installing MySQL on Ubuntu is one of the first steps.
But here's the thing: installing MySQL is easy. Installing it correctly with proper security and configuration is what separates a solid setup from a disaster waiting to happen.
In this guide, we'll walk through the complete process of installing and configuring MySQL on Ubuntu, from the initial installation through security hardening and optimization. By the end, you'll have a production-ready MySQL server running on your Ubuntu system.
Table of Contents
- Prerequisites
- Update Your System
- Install MySQL Server
- Verify the Installation
- Run MySQL Security Script
- Create a New MySQL User
- Configure MySQL for Optimal Performance
- Enable Remote Connections (Optional)
- Key Takeaways
Prerequisites
Before you start, make sure you have:
Ubuntu System Access
You need access to an Ubuntu system (20.04 LTS, 22.04 LTS, or later). You can use:
- A physical server
- A virtual machine (VirtualBox, VMware, etc.)
- A cloud instance (AWS EC2, DigitalOcean, Linode, etc.)
For more details on Ubuntu system requirements, see the official Ubuntu documentation.
Administrative Privileges
You need sudo access to run installation commands. This means either:
- Logging in as root user
- Being added to the sudoers group
Internet Connection
Your Ubuntu system needs internet access to download MySQL packages from repositories.
Terminal Access
You'll need to access a terminal (SSH if remote, or physical terminal if local).
That's it! You're ready to get started.
Update Your System
Before installing any new software, it's best practice to update your system's package lists and ensure everything is current.
Step 1: Update Package Lists
sudo apt update
This command fetches the latest package information from all configured repositories. It doesn't upgrade anything—just updates the list of available packages.
Step 2: Upgrade Installed Packages
sudo apt upgrade -y
The -y flag automatically answers "yes" to any prompts, so you don't need to confirm each upgrade manually.
This step is optional but recommended, especially on a fresh system. It ensures security patches and bug fixes are installed.
Why This Matters:
Outdated systems can have security vulnerabilities. By updating first, you're starting on a secure foundation.
Install MySQL Server
Now we're ready to install MySQL.
Step 1: Install MySQL Server Package
sudo apt install mysql-server -y
This command downloads and installs MySQL Server from Ubuntu's default repositories. The installation typically includes:
- MySQL server binaries
- MySQL client tools
- Configuration files
The installation might take 2–5 minutes depending on your internet speed and system resources.
Step 2: Verify Installation Started
sudo systemctl status mysql
You should see output showing MySQL is active (running). This means the service started automatically.
Understanding MySQL Versions:
The version you get depends on your Ubuntu version:
- Ubuntu 20.04 LTS: MySQL 8.0
- Ubuntu 22.04 LTS: MySQL 8.0
- Ubuntu 24.04 LTS: MySQL 8.0
MySQL 8.0 is the current stable version and what you'll get from the default repository. If you need a different version, you can add the official MySQL repository, but that's beyond this basic guide. For more details, see the official MySQL documentation.
Verify the Installation
Let's confirm MySQL is working properly.
Check MySQL Version
mysql --version
This shows the installed MySQL version. You should see something like mysql Ver 8.0.35.
Connect to MySQL
sudo mysql
This connects you to MySQL as the root user (with sudo). You should see a mysql> prompt.
Type exit to disconnect:
exit;
Test with Query
Back at the bash prompt, try running a query:
sudo mysql -e "SELECT VERSION();"
This shows the MySQL version from inside the database. You should see output like:
+---------------------+
| VERSION() |
+---------------------+
| 8.0.35-0ubuntu0.20 |
+---------------------+
Congratulations! MySQL is installed and running.
Run MySQL Security Script
MySQL comes with a security script that helps harden your installation. This is crucial for any production system.
Important: Ubuntu MySQL Configuration Note
Warning (As of July 2022): On Ubuntu installations, the root MySQL account is configured to use the auth_socket plugin instead of a password. This means the mysql_secure_installation script may encounter an error when trying to set a password for the root account.
Solution: Set Up Root Password First (Optional but Recommended)
If you want the root account to use a password instead of socket authentication, run these commands first:
sudo mysql
ALTER USER 'root'@" 'localhost' IDENTIFIED WITH mysql_native_password BY 'your_strong_password_here';
FLUSH PRIVILEGES;
exit;
Now you can run the security script without errors.
Run the Security Script
sudo mysql_secure_installation
This script will ask you several questions:
Question 1: Validate Password Plugin
Would you like to setup VALIDATE PASSWORD component?
Type y (yes). This enforces strong passwords.
Question 2: Password Validation Level
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
Choose MEDIUM for a good balance of security and usability (type 1).
Question 3: Remove Anonymous Users
Remove anonymous users?
Type y. Anonymous access is a security risk.
Question 4: Disable Root Login Remotely
Disable root login remotely?
Type y. This prevents attackers from accessing root from the network.
Question 5: Remove Test Database
Remove the test database and access to it?
Type y. Test databases are unnecessary in production.
Question 6: Reload Privilege Tables
Reload privilege tables now?
Type y. This applies all security changes immediately.
Why These Steps Matter
These security measures protect your database from common attacks:
- Strong password requirements prevent brute force attacks
- Removing anonymous users closes unnecessary access points
- Disabling remote root access limits attack surface
- Removing test databases removes unnecessary complexity
Create a New MySQL User
Never use the root account for regular database operations. Create a dedicated database user instead.
Connect as Root
sudo mysql
You're now in the MySQL command prompt (mysql>).
Create a New User
CREATE USER 'dbuser'@'localhost' IDENTIFIED BY 'strong_password_here';
Replace:
dbuserwith your desired usernamestrong_password_herewith a strong password (use a password manager!)
Grant Privileges
For a user managing all databases:
GRANT ALL PRIVILEGES ON *.* TO 'dbuser'@'localhost' WITH GRANT OPTION;
For a user managing only one database:
GRANT ALL PRIVILEGES ON database_name.* TO 'dbuser'@'localhost';
Apply Changes
FLUSH PRIVILEGES;
Verify the User
SELECT user, host FROM mysql.user;
You should see your new user listed.
Exit MySQL
exit;
Test the New User
mysql -u dbuser -p
It will prompt for a password. Enter the password you created. If successful, you're connected as the new user.
Configure MySQL for Optimal Performance
Default MySQL settings are conservative. For better performance, adjust key configuration parameters.
Edit MySQL Configuration File
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Or on some systems:
sudo nano /etc/mysql/my.cnf
Find the [mysqld] Section
Look for the section that starts with [mysqld]. This is where you add configuration.
Add/Modify These Settings
Find these lines and update them (or add them if missing):
--Buffer pool size (for caching frequently accessed data)
-- Set to 75% of available RAM
innodb_buffer_pool_size = 1G
-- Maximum connections allowed
max_connections = 200
-- Memory for sorting operations
sort_buffer_size = 256K
-- Memory for JOIN operations
join_buffer_size = 256K
-- Buffer size for each thread
thread_stack = 192K
Example Configuration
For a 4GB server, use:
innodb_buffer_pool_size = 3G
max_connections = 200
For a 1GB server, use:
innodb_buffer_pool_size = 750M
max_connections = 100
Save the File
If using nano, press Ctrl+X, then Y, then Enter.
Restart MySQL to Apply Changes
sudo systemctl restart mysql
Verify Changes
mysql -u root -p -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';"
This shows your new buffer pool size. For more configuration options and advanced tuning, see the MySQL Server Reference Manual.
Enable Remote Connections (Optional)
By default, MySQL only accepts connections from localhost for security. If you need remote connections, follow these steps.
Warning: Only do this if you need remote access. Local-only connections are more secure.
Edit MySQL Configuration
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Find this line:
bind-address = 127.0.0.1
Change it to:
bind-address = 0.0.0.0
This allows connections from any IP address. For more security, use a specific IP:
bind-address = 192.168.1.100
Restart MySQL
sudo systemctl restart mysql
Create Remote User
sudo mysql
CREATE USER 'remoteuser'@'%' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON *.* TO 'remoteuser'@'%';
FLUSH PRIVILEGES;
exit;
The % means "any host".
Test Remote Connection
From another computer:
mysql -h server_ip -u remoteuser -p
Replace server_ip with your Ubuntu server's IP address.
Key Takeaways
- Update system first — Always run
apt updateandapt upgradebefore installing new software. - Install MySQL — Single command
sudo apt install mysql-server -y. - Run security script —
mysql_secure_installationhardens your installation. - Handle socket authentication — Set root password first on Ubuntu 20.04+.
- Create dedicated users — Never use root for regular operations.
- Configure for performance — Adjust buffer pool, connections, and memory settings.
- Enable remote access carefully — Only if needed, and with proper security measures.
- Verify installation — Test with queries to confirm everything works.
- Monitor regularly — Check MySQL status and logs for issues.
Related Articles
Learn more about MySQL administration:
- How to Enable MySQL Slow Query Log — Monitor performance and identify issues
- MySQL Configuration Tuning: Optimize Server Resources — Advanced configuration for production systems
Need Help Setting Up Your MySQL Server?
Installation is just the beginning. Many teams struggle with:
- Proper security hardening
- Performance optimization
- Backup strategies
- High availability setup
Our database administrators can ensure your MySQL installation is:
- Secure and hardened against attacks
- Optimized for your specific workload
- Properly monitored and maintained
- Ready for production use
Request Your MySQL Setup Consultation or contact us at [+254 720 100 744] to discuss your specific needs.