For development purposes, you can easily run Spring Boot apps with Docker Compose.
Dockerize Spring Boot on development environment
Build a Docker image for your app
Firstly, we have to create a JAR file for our project. Run the following command in the project’s directory:
As a result, Maven builds the ready to use JAR file, as stated in docs:
The package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory.https://spring.io/guides/gs/maven/
Secondly, create the
Dockerfile file and copy the following code:
Make sure, that the ARG will contain the proper
target path. If your
Dockerfile isn’t in the same directory as the
target folder, the build process for a service called ‘app’ will exit with the following error:
You can fix it in two different ways:
- provide an absolute path to the
Dockerfileso it’s in the same directory as
Run Spring Boot with Docker Compose
docker-compose.yml file and put the following code in it:
- Our build context (
Dockerfile) is in the same folder as the compose file. Therefore we specify the location just with the
- We keep using the default 8080 port. As a result we still can access our app by visiting http://localhost:8080/.
- It’s likely that we want to enable communication between our Spring Boot app and other services that might be specified in the
docker-compose.ymlfile. Thus, we define a network that they can share.
Finally, we can run the application. Remember to use the name of your service instead of my name –
In case of any changes, rebuild the image:
In the end, you can verify whether the service was started by running in the console:
The output should be similar to the one presented in the screenshot below:
In addition, you can find the code responsible for building and running a Docker container with my Spring Boot project in the commit e2e4862fe782c5f3ac089ebcdf6521881f0794df.
Learn more on building Spring Boot apps with Docker
- Spring Boot in a Container
- Furthermore, you can use IntelliJ features to Run and debug a Spring Boot application using Docker Compose
- Spring Boot & Docker using VOLUME /tmp
- More on Docker