Search code examples
dockerdocker-network

How to create websocket connection between two Docker containers


I've got two Docker containers that need to have a websocket connection between the two.

I run one container like this:

docker run --name comm -p 8080:8080 comm_module:latest

to expose port 8080 to the host. Then I try to run the second container like this:

docker run --name test -p 8080:8080 datalogger:latest

However, I get the error below:

docker: Error response from daemon: driver failed programming external connectivity on endpoint test (f06588ee059e2c4be981e3676d7e05b374b42a8491f9f45be27da55248189556): Bind for 0.0.0.0:8080 failed: port is already allocated. ERRO[0000] error waiting for container: context canceled

I'm not sure what to do. Should I connect these to a network? How do I run these containers?


Solution

  • I finally worked it out. These are the steps involved for a two-way websocket communication between two Docker containers:

    1. Modify the source code in the containers to use the name of the other container as the destination host address + port number (e.g. comm:port_no inside test, and vice versa).

    2. Expose the same port (8080) in the Dockerfiles of the two containers and build the images. No need to publish them as they are will be visible to other containers on the network.

    3. Create a user-defined bridge network like this:

      docker network create my-net

    4. Create my first container and attach it to the network:

      docker create --name comm --network my-net comm_module:latest

    5. Create my second container and attach it to the network:

      docker create --name test --network my-net datalogger:latest

    6. Start both containers by issuing the docker start command.

    And the two-way websocket communication works nicely!