Docker communication between two containers with Java

前端 未结 2 1899
时光说笑
时光说笑 2021-01-07 03:39

There are two java files, Server.java and Client.java. Both are in separate containers.

DOCKER FILES: The dockerfile(in the folder named \'Server\')

2条回答
  •  孤城傲影
    2021-01-07 04:14

    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:

    • Create the network - sudo docker network create client_server_network
    • Run the server - sudo docker run --network-alias server --network client_server_network -it serverimage
    • Run the client - sudo docker run --network client_server_network -it clientimage
    • You should see message= Hello Server print in the server terminal

    Note 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:

    • Run the server - sudo docker run --name server -it serverimage
    • Run the client - sudo docker run --link server -it clientimage
    • You should see message= Hello Server print in the server terminal

提交回复
热议问题