Websocket interactions in Docker

I am trying to get my Websocket server (Java) and client (JS) to interact with each other when they are both running in separate Docker containers. However, no matter what I do, I cannot get the client to even establish a connection to the server. What can be done here?

Comments

Docker, among other things offer own networking solutions which are pretty handy to use.
Djordje Bulatovic - Fri, 12/11/2020 - 13:39 :::
2 answers

When starting docker a bridge network is automatically started, this network has its own ip and you have to check what is the ip of that network. If you are running it locally and used localhost, the bridge network's adress might be different from localhost and that might be why you weren't able to connect. However, using the containers' name is a much safer way to communicate between servers, docker will choose the correct address.

First of all, while there is more or less one stable option for Java, there exist many different libraries for JavaScript and some of them don't interact very well with Docker. As such, I recommend using the socket.io-client client library to implement the socket client.

Docker actually allows you to address your components via the names of their containers. So instead of using localhost or other IP addresses to connect to your container, you should specify the name of the container, for example use the address ws://socketserver:4001 if the name of the container that hosts the server is socketserver and it runs on port 4001. Furthermore, in your docker-compose file, you should make sure that there are no conflicts between exposed ports, and that the relevant port on the server is exposed. After that, your components should be able to interact with each other without any issues.