Spring Boot JPA with MySQL Docker

This guide is an expansion on the Accessing data with MySQL guide where instead we’ll connect to a Dockerised MySQL instance rather than a local installation.

Setup Spring Boot application

Check out the code from the official guide:

 git clone https://github.com/spring-guides/gs-accessing-data-mysql.git

We’ll be using the /completed source files.

If you’re new to Spring Boot JPA then it’s worth reading Accessing data with MySQL. If you don’t have a local installation of MySQL then as long as the source files are setup, this guide will walk you through the process of setting up a Docker MySQL database.

Setup MySQL container

Create a MySQL container and expose it on the host’s port 33067. I’ve selected this port as it’s unused on my machine (and most likely others too). However, if you don’t have a local MySQL installation (and don’t have any use for one) you can simply map to the default 3306 with -p 3306:3306 if that’s more familiar:

$ docker run --name mysql -e MYSQL_ROOT_PASSWORD=mypass123 -p 33067:3306 -d mysql:8.0.1

Setup the database and user:

$ docker exec -it mysql bash -l
# mysql -uroot -p
mysql> create database db_example;
mysql> create user 'springuser'@'%' identified by 'ThePassword';
mysql> grant all on db_example.* to 'springuser'@'%';

Change this line to point the Spring Boot app to the Docker MySQL. Remember to use the same port number as used when creating the MySQL container previously:


Run the app

Now as before build your app and run it:

$ mvn clean package
$ java -jar target/accessing-data-mysql-0.0.1-SNAPSHOT.jar

To test, from another terminal window:

$ curl localhost:8080/demo/add -d name=First -d email=someemail@someemailprovider.com
curl 'localhost:8080/demo/all'