Search code examples
dockerrustmqttmosquitto

Subscribing with my Rust program to MQTT in Docker doesn't work


I'm trying to run my Rust program as a Docker image and subscribe to Mosquitto MQTT broker also as a Docker image. The problem is, that I get an error which I don't get if I use the broker as a standalone service. I didn't changed anything in my code. Do you have any idea what's wrong with my code?

DEBUG [paho_mqtt::token] Token v5 failure! Token: 0xffffa0044b20, Response: 0xffffac874590
DEBUG [paho_mqtt::token] Token failure message: "TCP/TLS connect failure"
DEBUG [paho_mqtt::token] Token w ID 0 failed with code: -1
ERROR [isumis::service::subscriber_service] [-1] TCP/TLS connect failure
let host: String = env::args()
        .nth(1)
        .unwrap_or_else(|| "tcp://127.0.0.1:1883".to_string());
let id: &str = "isumis_backend";
let create_opts: CreateOptions = mqtt::CreateOptionsBuilder::new()
        .server_uri(host)
        .client_id(id)
        .finalize();

This isn't a problem in mosquitto because I can create a subscriber and publisher manually without any error messages. This error comes only when I subscribe with my program. The version of mosquitto is the same in Docker and as the local service (2.0.15).


Solution

  • 127.0.0.1 Always points to the TCP/IP stack that the current application is running in.

    Each docker container has it's own TCP/IP stack, so in this case 127.0.0.1 points to the container that the Rust application is running in, so there is no MQTT broker for it to connect to.

    You either need to change this to the IP address assigned to the container the MQTT broker is running in, or if you have mapped the broker port to the host machine you may be able to use the IP address of the host machine.

    The reason your manual test works is most likely because you are running on the host machine and you have mapped the ports.

    Try using 172.17.0.1 which is usually the IP address assigned to the host's docker0 interface.