Search code examples
spring-bootdocker-composespring-boot-docker-plugin

Spring Boot service calling another one, how to with spring-boot-docker-compose


I went through tutorials https://www.baeldung.com/docker-compose-support-spring-boot and https://www.youtube.com/watch?v=lS1GwdIfk0c . These explain how to make a Spring Boot application to use a dockerized product, e.g. some database.

But how about to make the Spring Boot service to call another my Spring Boot service, can spring-boot-docker-compose help?

I know to write docker-compose in terms of making two Spring Boot services communicate but what I don't know is how spring-boot-docker-compose can help.


Solution

  • Make the "another Spring Boot service" just another dockerized application and add it to your docker compose.

    So you need to:

    1. Create a Dockerfile for your service, something like this:
    FROM bellsoft/liberica-openjdk-alpine:17
    COPY target/yourapp-0.0.1-SNAPSHOT.jar /app/yourapp.jar
    ENTRYPOINT ["java", "-jar", "/app/yourapp.jar"]
    
    1. Build and publish the image to the local Docker repo. Go to the directory where the Dockerfile is and run docker build . -t tst/yourapp:0.0.1

    2. add it to your docker compose of the main service - set image, container-name, environment, ports, ... do not forget networks and giving your service access to the network of the to-be-called service and also depends_on to start it after it the all the to-be-called services...

    If the service communicates synchronously without some pooling/autor-reconnection or similar mechanism, you'll have to add connection retries via org.springframework.retry.support.RetryTemplate

    As for spring-boot-docker-compose, you just add it to your project as dependency, for maven it looks this way:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-docker-compose</artifactId>
    </dependency>
    

    Then you need to point to it from your application config, YAML version:

    spring:
      docker:
        compose:
          file: docker/compose-local.yaml
          enabled: true
          skip:
            in-tests: true
    

    When you start the app by mvn spring-boot:run or from IDE, spring-boot-docker-compose should start the container before it starts your app.