To use MySQL on a Linux server, install the MySQL server package for your distro, secure it with mysql_secure_installation, create a database and user, and connect via the mysql CLI.
Manage the service with systemctl, allow secure remote access if needed, and set up regular backups using mysqldump or binary logs. Learning how to use MySQL on a Linux server is a core skill for developers, sysadmins, and site owners.
This guide walks you through installation, hardening, basic operations, remote access, backups, and performance tuning using battle tested steps I use daily when deploying production databases on Ubuntu, Debian, Rocky/AlmaLinux, and CentOS servers.
What You’ll Need (Prerequisites)
- A Linux server (Ubuntu/Debian or RHEL-class like Rocky/AlmaLinux/CentOS).
- Shell access with sudo privileges.
- Open ports and firewall control (typically TCP 3306 for MySQL if remote access is required).
- Basic command-line comfort and understanding of SQL.
Tip: Decide whether you need Oracle MySQL or the community fork MariaDB. Many distros ship MariaDB by default. This tutorial focuses on MySQL, but most commands are similar for MariaDB.
Install MySQL on Linux
Ubuntu/Debian
Ubuntu’s repos may include MySQL or MariaDB. For the latest MySQL Community Server, use the official APT repo; otherwise, install from the distro repository.
# Update and install MySQL server
sudo apt update
sudo apt install -y mysql-server
# Verify service
sudo systemctl status mysql
Rocky Linux/AlmaLinux/CentOS (RHEL-family)
On RHEL-based systems, you can install MySQL from the official Yum repository for the latest version.
# Add the MySQL Yum repo (example for MySQL 8.0)
sudo rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el9-1.noarch.rpm
# Enable and install
sudo dnf install -y mysql-community-server
# Start and enable service
sudo systemctl enable --now mysqld
sudo systemctl status mysqld
Note: On first start in RHEL-family systems, MySQL may generate a temporary root password in the log (see the next section).
Initial Secure Setup
Harden your new MySQL instance immediately. This removes anonymous users, test DBs, and enforces better authentication.
# Ubuntu/Debian typically has socket auth for root and no default password
sudo mysql_secure_installation
On RHEL-based systems, retrieve the temporary root password from the log, then run the secure script:
# Find the temporary root password
sudo grep 'temporary password' /var/log/mysqld.log
# Run the secure installation
sudo mysql_secure_installation
Recommended choices during mysql_secure_installation:
- Enable password validation (medium or strong).
- Set a unique, strong root password (store it securely).
- Remove anonymous users and test database.
- Disallow remote root login (use per-app users instead).
Basic MySQL Usage from the Terminal
Log in to MySQL
# With a password
mysql -u root -p
# On Ubuntu with socket auth for root (no password prompt)
sudo mysql
Create a Database, User, and Assign Privileges
-- Inside the MySQL shell
CREATE DATABASE appdb DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create a dedicated app user (local server only)
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'ChangeThisStrongPassword!';
-- Grant least-privilege access
GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;
Run Simple SQL
-- Create a table, insert rows, and query
USE appdb;
CREATE TABLE posts (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200) NOT NULL,
published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO posts (title) VALUES ('Hello MySQL on Linux'), ('Second Post');
SELECT id, title, published_at FROM posts;
Service Management and Configuration
Use systemctl to manage the MySQL server process (mysqld).
# Start and enable at boot
sudo systemctl start mysql # Ubuntu/Debian (service name: mysql)
sudo systemctl enable mysql
# RHEL-family (service name: mysqld)
sudo systemctl start mysqld
sudo systemctl enable mysqld
# Check status and logs
sudo systemctl status mysql # or mysqld
journalctl -u mysql -n 100 --no-pager
Common configuration files:
- Ubuntu/Debian: /etc/mysql/mysql.conf.d/mysqld.cnf or /etc/mysql/my.cnf
- RHEL-family: /etc/my.cnf (with included directories)
Example tuning and network binding adjustments:
# Edit the mysqld section
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf # Ubuntu/Debian
# or
sudo nano /etc/my.cnf # RHEL-family
# Add/modify these lines under [mysqld]
bind-address = 127.0.0.1
sql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
innodb_buffer_pool_size = 1G # size to ~50-70% of RAM for dedicated DB servers
# Apply changes
sudo systemctl restart mysql # or mysqld
Secure Remote Access (Optional)
Expose MySQL externally only when necessary. Prefer private networking, SSH tunneling, or application and bastion hosts. If you must allow remote connections:
- Bind MySQL to a private IP instead of 0.0.0.0 when possible.
- Create a user restricted by host/IP.
- Firewall to known IPs only.
- Use TLS for client connections in production.
# 1) Bind to the server's private IP (example)
bind-address = 10.0.0.5
# 2) Create a user limited to an app server's IP
CREATE USER 'appuser'@'203.0.113.10' IDENTIFIED BY 'AnotherStrongPassword!';
GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'203.0.113.10';
FLUSH PRIVILEGES;
# 3) Open the firewall (Ubuntu)
sudo ufw allow from 203.0.113.10 to any port 3306
# firewalld (RHEL-family)
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="203.0.113.10" port protocol="tcp" port="3306" accept' --permanent
sudo firewall-cmd --reload
SSH tunnel alternative (no MySQL port exposure):
# From your local machine
ssh -L 3307:127.0.0.1:3306 user@your-linux-server
# Then connect MySQL client to local port 3307
mysql -h 127.0.0.1 -P 3307 -u appuser -p
Backups and Restores
Backups are non-negotiable. Use logical backups (mysqldump) for portability and recoverability, and consider physical or snapshot backups for very large datasets.
mysqldump Examples
# Backup a single database
mysqldump -u root -p --routines --triggers --single-transaction appdb > /backups/appdb-$(date +%F).sql
# Backup all databases
mysqldump -u root -p --all-databases --single-transaction > /backups/all-dbs-$(date +%F).sql
# Restore
mysql -u root -p appdb < /backups/appdb-2025-01-01.sql
Point in Time Recovery (Binary Logs)
Enable binary logging for PITR on production:
# In my.cnf/mysqld.cnf
log_bin = /var/lib/mysql/mysql-bin
server_id = 1
binlog_expire_logs_seconds = 604800 # 7 days
# After restart, list and apply logs as needed with mysqlbinlog
Automate backups with cron and test restores regularly. Store copies off-server (object storage) and encrypt when required.
Performance Essentials
- Use InnoDB for transactional workloads; it’s the default and best for most cases.
- Set innodb_buffer_pool_size to 50–70% of RAM on dedicated DB servers.
- Enable and review the slow query log; optimize queries and add indexes.
- Use EXPLAIN to study query plans and avoid full table scans.
- Keep schema normalized but pragmatic; use composite indexes for frequent filters/joins.
# Enable slow query log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
Scale up by increasing RAM/CPU, separating the database from the app/web tiers, and using read replicas when appropriate. Always baseline with sysbench and measure changes.
Troubleshooting Common Issues
- Cannot log in: Validate authentication method (unix_socket vs password). Reset root password in single-user mode if necessary.
- Service won’t start: Check logs (journalctl and MySQL error log), verify permissions on data directory, and config syntax.
- Port conflicts: Ensure nothing else is using 3306. Change the port if required.
- Access denied: Confirm user host (e.g., ‘user’@’localhost’ vs ‘user’@’%’) and privileges; run FLUSH PRIVILEGES.
# Where to look for logs
journalctl -u mysql -n 200 --no-pager
sudo tail -f /var/log/mysql/error.log # Ubuntu/Debian
sudo tail -f /var/log/mysqld.log # RHEL-family
Optional Tools: phpMyAdmin and Workbench
phpMyAdmin provides a web UI. Install it on a protected admin host, not on the public internet without strong access controls. MySQL Workbench (desktop) is handy for modeling and visual query execution; connect over SSH tunnels for security.
Self Managed vs Managed MySQL
Running MySQL yourself gives maximum control, but it also means handling updates, backups, monitoring, and incident response. If you’d rather focus on your application, YouStable offers Linux VPS and managed server options with optimized MySQL, regular backups, and security hardening—so your stack stays fast, safe, and up to date.
Best Practices Checklist
- Keep MySQL and the OS patched.
- Use least-privilege users per application.
- Restrict remote access and prefer private networking or SSH tunnels.
- Automate daily backups; test restores monthly.
- Monitor performance (CPU, RAM, I/O, slow queries); alert on anomalies.
- Document your schema, retention, and recovery procedures.
FAQ’s
How do I start and enable MySQL on Linux?
Use systemctl. On Ubuntu/Debian: sudo systemctl enable –now mysql. On RHEL-family: sudo systemctl enable –now mysqld. Check status with sudo systemctl status mysql (or mysqld) and review logs via journalctl for errors.
How do I connect to MySQL from the terminal?
Run mysql -u root -p and enter your password. On Ubuntu with socket authentication, use sudo mysql. For remote servers: mysql -h SERVER_IP -u USER -p (ensure firewall and grants allow your host).
Where is the MySQL configuration file on Linux?
Ubuntu/Debian typically use /etc/mysql/mysql.conf.d/mysqld.cnf (and /etc/mysql/my.cnf includes). RHEL-family systems use /etc/my.cnf with included directories. After edits, restart the service to apply changes.
How do I create a database and user quickly?
Inside the MySQL shell: CREATE DATABASE mydb; CREATE USER ‘myuser’@’localhost’ IDENTIFIED BY ‘StrongPass!’; GRANT ALL PRIVILEGES ON mydb.* TO ‘myuser’@’localhost’; FLUSH PRIVILEGES;. Always use strong, unique passwords and least privileges.
What’s the best way to back up MySQL on Linux?
For most workloads, use mysqldump with –single-transaction for consistent online backups, store off-server, and test restores. For large databases, consider physical backups and enable binary logs for point-in-time recovery. Schedule backups with cron and monitor success.
By following these steps, you can confidently install, secure, operate, and optimize MySQL on a Linux server—whether you’re running a small WordPress site or a mission‑critical SaaS platform. If you need performance-tuned Linux servers with expert support, consider YouStable’s VPS and managed solutions.