# MySQL and MariaDB basics on Ubuntu: install, users, backups

> MySQL and MariaDB are related open source relational databases that you install with apt or Docker, secure, then use through a limited user, mysqldump backups and a localhost-only bind address.

URL: https://levelrail.com/learn/databases/mysql-and-mariadb-basics/
Updated: 2026-11-27

Install MySQL or MariaDB with apt, run the secure-installation script, create a database and a limited user with `CREATE USER` and `GRANT`, and back up with `mysqldump --single-transaction`. Most web apps that need a MySQL-compatible server work with either one. MariaDB began as a fork of MySQL, so the commands below are the same for both unless a step says otherwise.

## How it works

The server process (`mysqld` or `mariadbd`) listens on TCP port 3306 and on a local Unix socket. Accounts are a user name plus the host the connection comes from, so `'app'@'localhost'` and `'app'@'%'` are different accounts. A new install has a `root` account that can administer everything. On Ubuntu and Debian packages, root authenticates through the Unix socket: if you are the operating system's root user (`sudo mysql`), you get in without a password, and a password login as root does not work.

Privileges are granted per account on global, database, table or column level. An app should get rights on its own database only. The `bind-address` setting decides which network interface accepts connections: the Debian default is `127.0.0.1`, which means local only. Keep it that way unless another machine truly needs access, and then limit port 3306 with a [firewall](https://levelrail.com/learn/glossary/#firewall)).

## Step 1: Install and secure

```bash
sudo apt update
sudo apt install mariadb-server
sudo systemctl status mariadb
sudo mariadb-secure-installation
```

For MySQL use `mysql-server`, the service `mysql`, and the script `sudo mysql_secure_installation`. The script walks through removing anonymous users, disallowing remote root login and removing the test database. Read each prompt. Accepting the defaults is sensible for a single server. The service is managed by [systemd](https://levelrail.com/learn/glossary/#systemd)), so `journalctl -u mariadb` shows its logs (see [read logs with journalctl](https://levelrail.com/learn/server-basics/read-logs-with-journalctl/))).

Open a shell as the database administrator:

```bash
sudo mysql
```

## Step 2: Create a database and an app user

```sql
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'app'@'localhost' IDENTIFIED BY 'change-me';
GRANT ALL PRIVILEGES ON shop.* TO 'app'@'localhost';
```

Replace `change-me` with a long random password. `shop.*` means every table in `shop` and nothing else. If the app runs in a container or on another host, the account host must match where it connects from, for example `'app'@'172.18.%'` or `'app'@'203.0.113.11'`. Check what exists with:

```sql
SELECT user, host FROM mysql.user;
SHOW GRANTS FOR 'app'@'localhost';
```

You do not need `FLUSH PRIVILEGES;` after `CREATE USER` and `GRANT`, because the server reloads the grant tables itself. It matters only if you edit `mysql.user` with `INSERT` or `UPDATE`, which you should avoid.

For a read-only account, grant only `SELECT`: `GRANT SELECT ON shop.* TO 'report'@'localhost';`. Test the new account:

```bash
mysql -u app -p shop -e "SELECT 1;"
```

The connection string form is in [database connection strings explained](https://levelrail.com/learn/databases/database-connection-strings-explained/)).

## Step 3: Back up with mysqldump

```bash
mysqldump --single-transaction --routines --triggers shop > shop-$(date +%F).sql
```

`--single-transaction` takes a consistent snapshot of InnoDB tables without locking them. `--routines` and `--triggers` include stored routines and triggers. Pass credentials through `~/.my.cnf` with `chmod 600` or `-u app -p`, and avoid putting `-pPASSWORD` on the command line, where other users can see it in the process list. Compress large dumps with `| gzip > shop.sql.gz`. Copy them off the server (see the [backup](https://levelrail.com/learn/glossary/#backup)) idea and [backups and the 3-2-1 rule](https://levelrail.com/learn/deploy-operate/backups-and-the-3-2-1-rule/))).

## Step 4: Restore a dump

```bash
mysql -e "CREATE DATABASE shop_check CHARACTER SET utf8mb4;"
mysql shop_check < shop-2026-11-27.sql
mysql -e "SELECT COUNT(*) FROM shop_check.orders;"
```

Restore into a scratch database first and compare row counts, as in [test a backup by restoring it](https://levelrail.com/learn/deploy-operate/test-a-backup-by-restoring-it/)). A dump that contains `DROP TABLE IF EXISTS` lines, which is the default, overwrites tables of the same name in the target database, so double check the database name before loading into a live one. For gzip files, use `gunzip < shop.sql.gz | mysql shop_check`.

## Step 5: Control network access

The settings file on Debian-based systems is in `/etc/mysql/` (MariaDB reads `/etc/mysql/mariadb.conf.d/50-server.cnf`). Look for:

```
[mysqld]
bind-address = 127.0.0.1
```

Change it to a private address only if remote clients need access, then `sudo systemctl restart mariadb` and allow port 3306 only from those clients. Never open 3306 to the whole internet. Containers on the same host can reach a host database through the Docker bridge, but a database container on a private network is usually simpler.

## Step 6: Run it in Docker instead

```bash
docker volume create mysqldata
docker run -d --name mysql \
  -e MYSQL_ROOT_PASSWORD=change-me \
  -e MYSQL_DATABASE=shop \
  -v mysqldata:/var/lib/mysql \
  -p 127.0.0.1:3306:3306 \
  mysql:8
```

`MYSQL_ROOT_PASSWORD` is required on first start and is read only when the data directory is empty. `MYSQL_DATABASE` creates a database on first start. Use the `mariadb` image for MariaDB, which accepts the `MARIADB_` prefixed variables as well. Open a shell with `docker exec -it mysql mysql -u root -p`. Bind to `127.0.0.1` for the same reason as with Postgres: Docker publishes ports around the host firewall.

## Check it worked

- `systemctl is-active mariadb` prints `active`.
- `sudo ss -ltnp | grep 3306` shows `127.0.0.1:3306`.
- `SHOW DATABASES;` as root lists `shop`, and `SHOW GRANTS FOR 'app'@'localhost';` shows only `shop.*`.
- A restore into `shop_check` gives the same row counts as `shop`.

## Edge cases and gotchas

- **The host part matters.** `'app'@'localhost'` does not match a connection from `172.18.0.3`. The error names the host it saw, so create the account for that host.
- **`localhost` is a socket.** The `mysql` client treats `localhost` as the Unix socket and `127.0.0.1` as TCP. An account for `'app'@'127.0.0.1'` does not cover the socket case.
- **Character sets.** Use `utf8mb4` for new databases, because the old `utf8` alias stores at most three bytes per character.
- **`skip-grant-tables` is an emergency tool.** It disables all authentication. Use it only briefly when locked out, never leave it on, and never with a network-reachable server.
- **Password plugins differ.** MySQL 8 defaults to `caching_sha2_password`, which some old clients cannot use. Check the client library before changing the plugin.
- **Dumps from another engine.** A MariaDB dump may contain syntax MySQL rejects, and the reverse. Test the restore on the target engine.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `ERROR 1698 (28000): Access denied for user 'root'@'localhost'` | Root uses socket auth | Run `sudo mysql` instead of `mysql -u root -p` |
| `ERROR 1045 (28000): Access denied for user 'app'@'localhost' (using password: YES)` | Wrong password or no matching account | Check `SELECT user, host FROM mysql.user;` and reset the password |
| `ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)` | Server not running | `sudo systemctl start mariadb` and check logs |
| `ERROR 2003 (HY000): Can't connect to MySQL server on '203.0.113.10:3306' (111)` | Nothing listening on that interface | Check `bind-address` and the firewall |
| `ERROR 1044 (42000): Access denied for user 'app'@'localhost' to database 'other'` | No grant on that database | Grant on the right database or fix the name |
| `ERROR 1049 (42000): Unknown database 'shop'` | Database not created | `CREATE DATABASE shop;` |
| `ERROR 1819 (HY000): Your password does not satisfy the current policy requirements` | Password validation plugin | Use a longer, more varied password |
| `mysqldump: Got error: 1045: "Access denied for user..." when trying to connect` | Missing credentials | Pass `-u` and `-p` or use `~/.my.cnf` |
| `ERROR 1130 (HY000): Host '172.18.0.3' is not allowed to connect to this MySQL server` | Account host does not match | Create the user for that host |

## Quick reference

```bash
sudo apt install mariadb-server && sudo mariadb-secure-installation
sudo mysql
mysql -u app -p shop
mysqldump --single-transaction --routines --triggers shop > shop.sql
mysql shop_check < shop.sql
```

```sql
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'app'@'localhost' IDENTIFIED BY 'change-me';
GRANT ALL PRIVILEGES ON shop.* TO 'app'@'localhost';
SHOW GRANTS FOR 'app'@'localhost';
```

## Related lessons

- [Install Postgres and connect with psql](https://levelrail.com/learn/databases/install-postgres-and-connect-with-psql/)): the same ideas on the other major server.
- [Database connection strings explained](https://levelrail.com/learn/databases/database-connection-strings-explained/)): the mysql:// URL form.
- [Postgres backup and restore with pg_dump](https://levelrail.com/learn/databases/postgres-backup-and-restore-with-pg-dump/)): compare it with mysqldump.
- [Set up a firewall with ufw](https://levelrail.com/learn/server-basics/set-up-a-firewall-with-ufw/)): keep 3306 closed to the world.
- [Manage secrets for self-hosted Docker apps](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)): where the app password goes.

## Next

Continue with [Redis basics, persistence and security](https://levelrail.com/learn/databases/redis-basics-persistence-and-security/)) for the in-memory side of your data stack.

## Frequently asked questions

### What is the difference between MySQL and MariaDB?

MariaDB started as a fork of MySQL and stays largely compatible for everyday use, but they are separate projects and have drifted in some features and tools. Most apps that support MySQL work with MariaDB.

### Do I need FLUSH PRIVILEGES after GRANT?

No. GRANT, CREATE USER and REVOKE reload the privilege tables themselves. FLUSH PRIVILEGES is needed only after editing the grant tables directly with INSERT or UPDATE.

### How do I back up a MySQL database?

Run mysqldump --single-transaction dbname > dbname.sql. For InnoDB tables it takes a consistent snapshot without locking writers.

### Why can I run sudo mysql without a password?

On Ubuntu and Debian, the root account uses unix socket authentication, so the operating system user root is trusted. Applications should use their own account with a password instead.


## Sources

- [MySQL reference manual](https://dev.mysql.com/doc/)
- [MariaDB knowledge base](https://mariadb.com/kb/en/)
