Back to blog

Setting Up MySQL with Docker

July 28, 2022·5

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,
unknown node

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
unknown node

This will create a new container with the name _<container_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:

unknown node

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
unknown node
  • Login into the MySQL shell using
unknown node

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
unknown node

References:

  • View this article on Instapaper with notes.
  • View the original one here.
Back to all posts
MySQL Database Setup with Docker | Khushal Bhardwaj