Home > OS >  How do I connect REST services (inside containers) together, in Spring Boot?
How do I connect REST services (inside containers) together, in Spring Boot?

Time:05-05

I'm supposed to build a system with individual REST services using docker compose. One of them is a web app where a user can login, and one of them is an authentication service, so I need to connect to the rest authentication service using a post request, and get the confirmation.

This is my authentication service:

@RestController
public class AuthenticationController {
    private final List<User> users=GetUsers();

    @PostMapping ("/verify")
    public String greeting(@RequestParam String username, @RequestParam String password) {
        for (User u :users)
            if (u.getUsername().equals(username)&&u.getPassword().equals(password))
                return u.getRole();
        return "Invalid Credentials ";

    }
} 

So, how exactly do I connect from inside the web app code into this service and send a post request?

I know I can send a get using this:

String uri = "http://localhost:8080/verify";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

How would I send a post? And how would it work inside containers? I know I can link them together inside docker compose, but how do I do it on the code level? Do I replace the localhost:8080 with containerName:exposedPort?

CodePudding user response:

As you know, Docker containers are individual Linux virtual machines which means localhost inside a Docker container refers to the container itself, not the host.

Docker compose has a feature called DNS resolutions which basically means you can call other services by their container name or container hash id.

So in your web app, you can call API by containerName:containerPort instead of localhost.

For more information, look at this complete implementation.

  • Related