For development purposes, you can easily run Spring Boot apps with Docker Compose.
We’re going to start a Spring Boot application written in Java 11 (OpenJDK) in a container. Additionally, you can see the example spring-boot-log4j-2-scaffolding project for more details.
Firstly, we have to create a JAR file for our project. Run the following command in the project’s directory:
$ mvn package
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:
# Dockerfile
FROM openjdk:11-jdk-slim
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
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:
Step 4/5 : COPY ${JAR_FILE} app.jar
ERROR: Service 'app' failed to build: COPY failed: no source files were specified
You can fix it in two different ways:
target
;Dockerfile
so it’s in the same directory as target
.Create the docker-compose.yml
file and put the following code in it:
# docker-compose.yml
version: "3.3"
services:
app:
build:
context: ./
ports:
- "8080:8080"
networks:
- internal
networks:
internal:
Dockerfile
) is in the same folder as the compose file. Therefore we specify the location just with the ./
path.docker-compose.yml
file. 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 – app
:
$ docker-compose up -d app
In case of any changes, rebuild the image:
$ docker-compose up -d --build app
In the end, you can verify whether the service was started by running in the console:
$ docker ps
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.
Photo by Retha Ferguson from Pexels
Spring Security allows us to use role-based control to restrict access to API resources. However,…
A custom annotation in Spring Boot tests is an easy and flexible way to provide…
Delegating user management to Keycloak allows us to better focus on meeting the business needs…
Swagger offers various methods to authorize requests to our Keycloak secured API. I'll show you…
Configuring our Spring Boot API to use Keycloak as an authentication and authorization server can…
Keycloak provides simple integration with Spring applications. As a result, we can easily configure our…