DEV Community

Cover image for Spinning up MySQL Database with Docker
Khushal Bhardwaj
Khushal Bhardwaj

Posted on • Edited on

Spinning up MySQL Database with Docker

This article was originally published on my blog, visit it here.

This is the best way to start since you don't have to install MySQL locally and configure it and run into like thousands of issues and in the end not being able to make it, docker makes it much easier for me or probably for you also to spin up a MySQL database in minutes.

To get started, follow these steps:

  • Pull the latest image,
docker pull mysql:latest
Enter fullscreen mode Exit fullscreen mode

You don't have to do it manually, it will download automatically if not installed when we spin up the container.

  • Start the container using the following command
docker run --name <container_name> -p 3306:3306 -v mysql_volume:/var/lib/mysql/ -d -e "MYSQL_ROOT_PASSWORD=<root_password>" mysql
Enter fullscreen mode Exit fullscreen mode

This will create a new container with the name , with the mysql:latest image, and publish the ports 3306 to the local environment to use the instance outside the container.

This also sets up the volume for the container to persist the database's data, so that it doesn't reset on restarts of the host system or the container.

We also pass in the environment variable MYSQL_ROOT_PASSWORD to set a root password for the database.

If not provided, it will generate a random strong password, we can see it in the container logs using this command:

docker container logs <container_name>
Enter fullscreen mode Exit fullscreen mode

You can pass in the following Environment Variables when starting the container:

  • MYSQL_ROOT_PASSWORD: Set up your password using this environment variable.
  • MYSQL_ALLOW_EMPTY_PASSWORD: Blank or Null password will be set. You have to set MYSQL_ALLOW_EMPTY_PASSWORD=1.
  • MYSQL_RANDOM_ROOT_PASSWORD: a random password will be generated when the container is started. You have to set MYSQL_RANDOM_ROOT_PASSWORD=1 to generate the random password.

Don't pass in the permanent password in production, as the password will be visible in the shell history, which we obviously don't want.
A possible solution is that we pass in a temporary password like temp123 and then change it afterwards.

We can change the root password as follows:

  • Get into the container using
docker exec -it <container_name> bash`.
Enter fullscreen mode Exit fullscreen mode
  • Login into the MySQL shell using
mysql -u root -p
Enter fullscreen mode Exit fullscreen mode

This will prompt you to enter the password which we set up before, in our case it was temp123.

  • After logging into the shell, run the following SQL query to change the password
ALTER USER 'root'@'localhost' IDENTIFIED BY '<new_password>';
Enter fullscreen mode Exit fullscreen mode

References:

  • View this article on Instapaper with notes.
  • View the original one here.

Top comments (0)