How do you set up MySQL and log in to it?

BeginnerHands-onMySQL
Answer

Short answer

The quickest way is to run MySQL in Docker with a root password, then log in with the mysql client: mysql -u root -p. On a server you can also install it with the package manager (apt install mysql-server).

Option 1 — Docker (best for learning and testing)

docker run -d --name mysql \
  -e MYSQL_ROOT_PASSWORD='Root@123' \
  -e MYSQL_DATABASE=shop \
  -p 3306:3306 \
  -v mysql-data:/var/lib/mysql \
  mysql:8.4

docker exec -it mysql mysql -u root -p      # log in inside the container
  • -e MYSQL_ROOT_PASSWORD sets the root password.
  • -e MYSQL_DATABASE=shop creates a database called shop at start.
  • -v mysql-data:/var/lib/mysql keeps the data even if the container is deleted.

Option 2 — Install on Ubuntu

sudo apt update && sudo apt install -y mysql-server
sudo systemctl enable --now mysql
sudo systemctl status mysql
sudo mysql                       # on Ubuntu, root logs in through the system root user

Logging in

mysql -u root -p                             # local, asks for the password
mysql -h db.internal -P 3306 -u app_user -p shop   # remote host, port, user, database
Option Meaning
-u Username
-p Ask for the password (don't type the password after -p in shared terminals — it ends up in history)
-h Host to connect to (default: localhost)
-P Port (default: 3306)

What to say in the interview

"For local testing I run MySQL in Docker with MYSQL_ROOT_PASSWORD and a volume for persistence, and log in with mysql -u root -p. On servers it's installed through apt or dnf and managed with systemctl. In production on AWS we usually use RDS for MySQL, and connect with mysql -h <endpoint> -u <user> -p. The default port is 3306."

Follow-up questions you may get

  • Where does MySQL keep its data? In /var/lib/mysql by default.
  • Where's the config file? /etc/mysql/my.cnf (Ubuntu) or /etc/my.cnf (RHEL).
All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MySQL basics

More on MySQL