Techscrypt

How to setup MySQL in Docker

mysqldocker

Why you should run databases in docker for local development

Installing and maintaining a local version of a database can take up a lot of valuable time. Setting up a database in docker can help save that time, and make the the installation a lot more portable, since docker containers can be moved around.

If you have multiple applications that need different versions of MySQL on your local machine, then running each of them in a docker container can make it a trivial task.

If you are new to docker, read up here — https://www.docker.com/products/docker-desktop. Assuming you have docker setup on your machine, following steps illustrate how to setup a MySQL database in a docker container

Create a container running MySQL

docker run -p <host_machine_port>:3306 --name <container_name> -e MYSQL_ROOT_PASSWORD=<root_password> -e MYSQL_DATABASE=<db_name> -d mysql:<version>

Let us look at all the parameters in the above command

<host_machine_port> — The port on your local machine that you want the container connected to. For example, if you want the mysql instance on localhost:3310, your <host_machine_port> would be 3310

<container_name> — The name of the container that will be created

<root_password> — The password for the root user on the mysql instance.

<db_name> — The name of the database that will be created

<version> — The version of MySQL that you want to run

For example, if you want to create a MySQL instance using the latest version of MySQL with a database called people with a root password = my_password connected to your local machine port 3310, the following command would accomplish that.

docker run -p 3310:3306 --name sql_db -e MYSQL_ROOT_PASSWORD=my_password -e MYSQL_DATABASE=people -d mysql

Verify container status using this command

docker container ls

The above command will display all the docker containers running on your machine, and you should see your newly created container.

Connect to the database instance

Now you can connect to the mysql instance using the mysql command if you have it installed on your local machine: mysql --host=127.0.0.1 --port=3310 -uroot -p. But given the fact that we did not want to install mysql on our local machine in the first place, it would be better if we connect to the database using shell access inside the container.

Get shell access inside the docker container using

docker exec -it <container_name> bash

And then run mysql -p inside the container.

References

  1. MySQL
  2. Docker Desktop

Subscribe to the Newsletter

We will only use your email address to send out the weekly newsletter with the latest updates from Techscrypt.

* indicates required