0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Hamid
  • 679
  • 1
  • 7
  • 22
  • this is great thanks !, but i still cant do a post request, keep getting error 400 bad request , when i try like this : RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/verify"; Map map = new HashMap<>(); map.put("username", username); map.put("password", password); ResponseEntity response = restTemplate.postForEntity(url, map, String.class); – Grim Ranger May 04 '22 at 08:16
  • 1
    First, you should not use *localhost*!, then if you want to send body with post request, you should send it throughout `@RequestBody` and not `@RequestParam`, or put parameter inside URL with something like this: https://stackoverflow.com/a/36021268/8004901 – Hamid May 04 '22 at 08:43
  • im using localhost because im testing outside containers, and yep, i just figured out the @RequestBody a second ago, that was dumb of me, thats a few hours of my life i'll never get back lol, anyway thank you very much , youve been a ton of help. – Grim Ranger May 04 '22 at 08:47