There are two java files, Server.java and Client.java. Both are in separate containers.
DOCKER FILES: The dockerfile(in the folder named \'Server\')
There are 3 problems:
Also, there's no need for the EXPOSE directive in the client Dockerfile.
For modern docker versions (1.13+)
To understand where this approach goes wrong, the docker networking guide has all of the intricate details, but it largely boils down to the fact that you can't simply reference localhost
in one container and expect it to route to another container running on your host.
By default each container runs on a bridge network, and each container effectively appears as a separate host on that bridge network, in the same subnet. The containers can reference other containers via their assigned IP address on the bridge network, but localhost
simply refers to the container itself, rather than the underlying host that's running the container.
To achieve predictable routing similar to what you're after, you can define your own bridge network and run the client and server containers on that user-defined network. This does require one small code change in your Client.java
. Instead of localhost
, you have to address the server with a chosen alias, say server
. Once you've edited the client code and rebuilt clientimage
, try the following:
sudo docker network create client_server_network
sudo docker run --network-alias server --network client_server_network -it serverimage
sudo docker run --network client_server_network -it clientimage
message= Hello Server
print in the server terminalNote that I provided an additional --network-alias server
to the server's docker run
, to add a network alias where the client can predictably reach the server container. You have multiple ways of achieving that aliasing, including using the --name
option, but check out the docker embedded dns docs for more details.
For older docker versions (1.12-)
Docker provides a container linking functionality, exposed via the --link
option supplied to docker run
. You'll need some of the same updates as above, notably using something like server
in place of localhost
, and running the server container with --name server
. The docker run would look like:
sudo docker run --name server -it serverimage
sudo docker run --link server -it clientimage
message= Hello Server
print in the server terminal