Skip to main content

Docker - Mysql as a Container


How do you(we) run Mysql database in our development, QA or production environment? Install required packages, configure, open ports, monitor as necessary. So many things to do and it is repeating over all the environments. Why repeat when we have Docker!

First make sure you have installed Docker.
docker -v

Get the MySQL image

Let's pull the Mysql image from the docker hub.
Official MySQL docker image
docker pull mysql

Make sure it is downloaded.
docker images

Creating the MySQL container

Let's create a container from it and go inside.
docker container run -d -p 3306:3306 --name mysql-test -e MYSQL_ROOT_PASSWORD=secret mysql
docker exec -it mysql-test bash

Now we are inside our mysql docker container. We can use all our mysql commands from here.
# mysql -uroot -p
# Enter password:secret
# create database docker-test

Type exit to exit from the container.

Inspecting the container

Check and inspect our container to get more details.
docker container mysql-test ls
docker container inspect mysql-test

Connecting from localhost

We can connect to container using host's mysql client as below.
mysql -h -P 3307 -u root -p secret
mysql -h localhost -P 3307 --protocol=tcp -uroot -psecret

Adding a bind mount

We can define a directory for mysql data storage. In this way we can save database even the container is removed.
First create a directory in host machine.
mkdir -p /docker/test/mysql-datadir
Bind it as below.
docker run \
--detach \
--name=mysql-test \
--publish 3306:3306 \
--volume=/docker/test/mysql-datadir:/var/lib/mysql \

Removing the container

Once we are done with our work we can easily remove the running container.
docker container stop mysql-test
docker container rm mysql-test
docker container -f rm mysql-test

That's it!