TakeHost
← All tutorials

Server Management

How to Install and Secure MySQL/MariaDB

Intermediate15 minMySQLMariaDBDatabaseSecurity

MariaDB is a drop-in MySQL-compatible database. This guide installs it on Ubuntu 24.04, runs the hardening script, binds it to localhost so it is never exposed to the internet, and creates a dedicated least-privilege user for your application. Applications should never connect as root.

/01

Install MariaDB

Install the server and confirm the service is running.

sudo apt update
sudo apt install -y mariadb-server
sudo systemctl enable --now mariadb
systemctl status mariadb --no-pager   # verify it is active (running)
/02

Run the Hardening Script

mysql_secure_installation removes anonymous users and the test database, disables remote root login, and lets you set the root password. Answer yes to every hardening prompt.

sudo mysql_secure_installation
# Recommended answers: set a strong root password, then Y to remove anonymous users,
# Y to disallow remote root, Y to remove the test DB, Y to reload privileges.
/03

Bind to Localhost Only

Confirm the server listens only on 127.0.0.1 so it is unreachable from the internet. This is the single most important network setting for a database.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf
# Ensure this line is present and NOT commented out:
bind-address = 127.0.0.1   # accept connections only from this machine
sudo systemctl restart mariadb
/04

Create a Least-Privilege Application User

Create one database per app and a user that can touch only that database. Use a long random password, not a dictionary word. Never hand applications the root account.

sudo mysql
-- Inside the prompt:
CREATE DATABASE myapp;
-- 'localhost' restricts this user to local connections only
CREATE USER 'myappuser'@'localhost' IDENTIFIED BY 'CHANGE_ME_long_random_password';
-- Grant rights ONLY on myapp.*, never on *.* (which would be server-wide)
GRANT ALL PRIVILEGES ON myapp.* TO 'myappuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
/05

Verify the Application User Can Connect

Log in as the new user to confirm the credentials and grants work, and that it sees only its own database.

mysql -u myappuser -p myapp   # enter the password; you should land in the myapp database
# Inside, run: SHOW DATABASES;  -- you should see only myapp (plus information_schema)
# Then: EXIT;
/06

Confirm It Is Not Listening Externally

Double-check the bind succeeded so the database is not reachable from outside the host.

sudo ss -tlnp | grep 3306   # should show 127.0.0.1:3306, NOT 0.0.0.0:3306

MariaDB is installed, hardened, bound to localhost, and accessed by a least-privilege user scoped to a single database. If a remote app truly needs access, prefer an SSH tunnel or a private network over exposing port 3306, and always use strong unique passwords.

Ready when you are

Deploy it on TakeHost.