I had a interview 3 years back and in one of the design interview rounds a question came up ,how can you have two java application (Deployed on tomcat) run on the same port . You can use any tools like docker etc but you can’t have a separate virtual machine (like Vmware or VM virtual box) . I am not sure if docker can be used (I just said may be we can use two docker containers, not sure if it would be the right approach) . Any ideas if its possible and how .
3
Answers
You can’t have 2 programs that use the same port.
To solve that, you can set up a reverse proxy (Nginx, Traefik or the like) that listens on the port and then routes the traffic to the applications based on what the requests look like. The applications would listen on their own ports. So one port each.
You can route on different things, but in your case you might set it up so requests that start with
/app1/
go to one application and requests that start with/app2/
go to the other.Nginx and Traefik both have standard images available that are pretty easy to set up in Docker.
You can’t have two processes listen to the same ports on the same IP address on the same machine.
To work around this, as Hans Kilian says, you’ll need a reverse proxy.
Alternatively, if the machine’s network interfaces are configured for multiple IP addresses, you can assign one to each running server – and then you’re free to use the same port on the other IP-address(es). This is independent of the actual server that you use – be it Tomcat, Docker, or anything else.
Naturally, configuring the different processes to listen to specific IP addresses is dependent on the software itself. As you’re asking about Tomcat: It’s connectors (see server.xml) have the configuration.
I consider Reverse Proxies more the standard approach found in the wild, but as you were talking about an interview question: This is another option
The only approach to have this scenario is to use reverse proxy which can route the request to the specific java applications based on url match and redirect logic.
The apps must be running on different ports, eg. in case of nginx as proxy create two server blocks with each having a location block.