Open a WebSocket connection to a docker container to another (capable of pinging the container in the cli, but not via ws)

I am using docker-compose to run 2 containers, 1 to run the app-app and the other to run the rabbitmq server.

version: '2'
services:
    node.app.local:
        build:
            context: ./node
        container_name: app-node
        hostname: node.app
        domainname: local
        tty: true
        volumes:
            - "${SOURCES_PATH}/app:/var/www/app"
        ports:
            - 8091:8091
        expose:
            - 8091
        links:
            - rabbitmq.app.local
        working_dir: "/var/www/app"

    rabbitmq.app.local:
        image: rabbitmq:3.6.10
        container_name: app-rabbitmq
        hostname: rabbitmq.app
        domainname: local
        tty: true
        expose:
            - 5672
            - 15672
            - 15674

      

I know that communication between my node container and my rabbitmq server works well, as I can ping the server from my node container:

$ docker exec -it app-node bash
$ ping rabbitmq.app.local

      

64 bytes from 172.18.0.12: icmp_seq = 0 ttl = 64 times = 0.099 ms

64 bytes from 172.18.0.12: icmp_seq = 1 ttl = 64 times = 0.098 ms

64 bytes from 172.18.0.12: icmp_seq = 2 ttl = 64 times = 0.069 ms

64 bytes from 172.18.0.12: icmp_seq = 3 ttl = 64 times = 0.088 ms

In my js app, if I open a connection to the server IP (172.18.0.12 as shown by ping), it works well:

const ws = new WebSocket('ws://172.18.0.12:15674/ws');
//connected to server RabbitMQ/3.6.10

      

But if I try with the container name:

const ws = new WebSocket('ws://rabbitmq.app.local:15674/ws');

      

VM7698: 35 WebSocket connection with 'ws: //rabbitmq.app.local: 15674 / ws' failed: error in establishing connection: net :: ERR_NAME_NOT_RESOLVED

Does anyone know why I can ping a server in the CLI but cannot access it via the ws protocol?

+3


source to share


1 answer


I faced the same issue when using PHP in one container connecting to a websocket service in another container.

I did some research and found that docker compose v2 uses custom networks which in terms of injecting a built-in DNS server, replacing the traditional DNS inside a container on the default bridge network.

The built-in DNS server maintains a mapping between all container aliases and its IP address on a specific custom network.



How it works is according to the official docker document. But it seems that there are some issues when trying to DNS-resolve the alias or container reference mentioned by jake-low , docker-compose contributor.

So, an alternative solution to this problem is to first get the IP by hostname and then use the resolved IP to connect to the websocket service. This is how I solve the problem.

+1


source







All Articles