How to run MySQL server inside a docker container using docker-compose.yml

rizahorasan
3 min readMay 26, 2021

--

In this simple tutorial, we will see how easy to run a MySQL Server in a docker container using docker-compose.yml file.

To get a running container I will use Docker Desktop for Windows (when Docker Desktop is installed, you will have Docker Engine, Docker CLI client and Docker Compose), GitBash, Visual Studio Code and MySQL Workbench.

Let’s start.

  1. Create a folder named how_to_run_mysql_docker. All the required files and folders will be created in this folder.
  • Create a file named docker-compose.yml. Since this is a yml file, be careful about the indentation.

simple-docker-mysql defines the service name.

container_name: simple-docker-mysql defines the container name.

image: mysql defines the base docker image that we will use.

environment section defines the schema properties that will be created.

ports section is about the ports that we will use while connecting to MySQL server which is inside the container. In this case, MySQL Server will be running on 3306 inside the container. And port 5005 will be used while connecting from outside of the container.

volumes section is optional. With this entry, sql files (inside the sql_init folder) will be executed in the container start up process.

  • Create a folder named sql_init. In sql_init, create a file named tables.sql.

Now, you will have a folder structure as follows.

Folder structure.

We are almost there.

Go to how_to_run_mysql_docker in GitBash. Run the following command to create MySQL container.

Check the container status. You should see the new container’s status as up.

New container is up.

2. Now, it is time to connect to MySQL server instance.

  • Open MySQL Workbench. Click new connection button. You can give any connection name.
  • Port is 5005 (this port is defined in the docker-compose.yml file).
  • password is passworddb (this password is defined in the docker-compose.yml file).
MySQL connection.
  • Click OK. Now, you are connected to MySQL instance inside the docker container. You can see the results of the SQL scripts (sql_init/tables.sql).

3. If you want to stop and remove the MySQL container, go to how_to_run_mysql_docker folder in GitBash. Run the following command to remove the MySQL container.

That’s all. With these simple steps, you have your own MySQL instance on your local machine. You can download the source file from the following repository.

--

--

rizahorasan
rizahorasan

Written by rizahorasan

software developer, software architect, software something.