Skip to main content

Installing MySQL in a container and creating a new database

MacBook Pro with images of computer language codes

MySQL is a very popular database engine. Usually, chances are you probably don’t wake up one day wanting to install MySQL. Instead, you most likely have a software package which requires a MySQL database, and so adding this engine is a side effect, so you want to do it as quickly and efficiently as possible. Here we will cover how to install the database as a Docker container, and then how to create a new user and database for it.

The first thing to do is making sure Docker is installed. You can see my earlier post on how to do that.

Once Docker is installed, use this command to install MySQL, along with the root password you wish:

docker run --name mysql -v /mysql_content:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=mypassword -d mysql:latest 

After that, you can enter the container and run a shell in order to start the mysql client:

docker exec -it mysql /bin/bash
mysql -u root -p

Finally, you can create a new user and database according to the needs of the software package you’re trying to install. Typically, these commands will do it:

CREATE DATABASE mydb;
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'%';
FLUSH PRIVILEGES;
QUIT

That’s it! Now all you need to do is configure the software package with the details you’ve entered. In order to find out which IP address to use for the MySQL container, you can use the docker inspect mysql command.