How to connect a MySQL Docker Container to a Spring Boot Application running locally
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.
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.
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.
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
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.
Here you can create a database, a user and grant him/her access to it.
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.
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.
This is all, hope this was helpful! Do write down any of your thoughts as comments below.