How to connect a MySQL Docker Container to a Spring Boot Application running locally

Rui Le Gan
3 min readMay 12, 2021

If you do not want to install MySQL Server and MySQL Workbench directly into your Windows machine, you can obtain it from Docker, and still link it to your Spring Boot Application running locally. Here’s how!

Create docker-compose.yml file

First, create a docker-compose.yml file in a directory you want.

docker-compose.yml

There are 2 images we specified— “mysql” and “adminer”. Adminer allows us to conveniently manage the databases created without having to use MySQL Workbench. It can also work for other databases such as PostgreSQL and MongoDB.

Start your Docker desktop app

Don’t miss out this step!

Run docker-compose up

In the directory of the docker-compose.yml, run docker-compose up. This starts the MySQL and Adminer containers, bound to a command prompt terminal. You can see the logs there. On a command prompt, you can run docker container ls -a to view the containers in your system.

containers

In addition, you can head on to localhost:9000 to view the Adminer database management interface and login as the root user using the password defined in docker-compose.yml.

Adminer interface @ localhost:9000

Start the interactive Bash shell in the MySQL Container

You can either do so via the Docker Desktop app (shown below), or by opening a new command prompt and entering docker exec -it <container name or ID> bash

opening the interactive Bash shell by clicking on the CLI icon, using the docker desktop app

Run MySQL Commands

If you want to run MySQL Commands through the MySQL Shell, first enter mysql -uroot -p<root password> where root password is what you defined in the docker-compose.yml file. This will bring you into the MySQL Shell.

Going from Bash to MySQL Shell

Here you can create a database, a user and grant him/her access to it.

usual MySQL Commands

Configure your Spring Boot application.properties file

Now, in your Spring Boot application, define some properties to allow it to connect with the MySQL container.

application.properties file

Run your Spring Boot application. Then, head to your Adminer interface, click on the refresh button and you should see your new database appear. You can click on it and see the tables and manage the database through the interface if you would like to.

sample table in the Adminer interface

This is all, hope this was helpful! Do write down any of your thoughts as comments below.

--

--