MySQL is one of the world's most widely used relational database systems, powering WordPress, Laravel, Magento, WHMCS, and thousands of other applications. This guide covers installation, initial security hardening, and creating your first database and user.
Prerequisites
- Ubuntu 22.04/24.04 or Debian 11/12 VPS
- Root or sudo access
Step 1 — Update the System
sudo apt update
sudo apt upgrade -y
Step 2 — Install MySQL Server
sudo apt install mysql-server -y
Step 3 — Enable and Start MySQL
sudo systemctl enable mysql
sudo systemctl start mysql
sudo systemctl status mysql
Step 4 — Secure the Installation
sudo mysql_secure_installation
Recommended answers:
- Validate password policy: Yes
- Set/confirm a strong root password
- Remove anonymous users: Yes
- Disallow remote root login: Yes
- Remove the test database: Yes
- Reload privilege tables: Yes
Step 5 — Log In
sudo mysql
Step 6 — Create a Database
CREATE DATABASE myapp;
Step 7 — Create a Dedicated User (Never Use Root for Applications)
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'CHANGE_ME_STRONG_PASSWORD';
GRANT ALL PRIVILEGES ON myapp.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Verifying the Installation
mysql --version
mysql -u appuser -p myapp
Common Errors
"Access denied for user" — double-check the username, password, and that GRANT/FLUSH PRIVILEGES were run.
MySQL won't start — check logs:
sudo journalctl -u mysql
"Public Key Retrieval is not allowed" (some client tools) — occurs with the default caching_sha2_password auth plugin; either add allowPublicKeyRetrieval=true to the client, or switch the user to legacy auth if the client doesn't support it.
Best Practices
- Never use the root MySQL account for application connections
- Create a separate database and user per application
- Restrict remote access unless explicitly required; if needed, limit by IP
- Set up regular backups — see How to Back Up and Restore MySQL/MariaDB Databases
FAQ
What's the difference between MySQL and MariaDB?
MariaDB is a community-developed fork of MySQL, designed as a largely compatible drop-in replacement with some additional features and a fully open development model.
Related Articles
- How to Back Up and Restore MySQL/MariaDB Databases
- How to Tune MySQL/MariaDB Performance for a VPS
- How to Install MariaDB on Ubuntu & Debian
