Last updated

Homelab

Install MySQL on Ubuntu 24.04 and 22.04 (Secure Setup)

Install MySQL Server from Ubuntu's own packages, run the security script, and create a dedicated user for your app instead of using root. Ubuntu 24.04 ships MySQL 8.0.

Related guide: Full MySQL / MariaDB setup guide

1. Install MySQL

Installs MySQL Server and starts it.

sudo apt update
sudo apt install mysql-server
sudo systemctl status mysql

2. Run the security script

Removes anonymous users and the test database, and turns off remote root login. On Ubuntu, root uses auth_socket, so it logs in with sudo and no password.

sudo mysql_secure_installation

3. Open the MySQL shell

As root through sudo, using auth_socket.

sudo mysql

4. Create a user for your app

Give each app its own user and database, and only the rights it needs.

CREATE DATABASE appdb;
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'a-long-random-password';
GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

5. Test the new user

Log in as the new user and list its databases.

mysql -u appuser -p -e 'SHOW DATABASES;'

FAQ

Why can root log in without a password?

On Ubuntu, MySQL's root account uses the auth_socket plugin, so only the Linux root user (through sudo) can log in as MySQL root. That is safer than a password.

Should I open port 3306 to the internet?

No. Keep MySQL on localhost, or allow 3306 only from specific app servers, and use an SSH tunnel for remote admin.