Reputation: 1125
i have a test container containing a python script unit test to test the connection to a mqtt broker. The mqtt broker is another docker container using eclipse-mosquitto:latest.
I have also created a docker network.
Below are the docker statements:
docker network create test_network
docker run -d -p 21883:1883 --name=gatewaymqtt --network=test_network -v "$PWD/work/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf" -v "$PWD/work/mosquitto/data:/mosquitto/data" -v "$PWD/work/mosquitto/log:/mosquitto/log" eclipse-mosquitto:latest
docker build -t test -f ./Dockerfile-test .
docker run --network=test_network test
Inside the test container it is running this python unit test:
class TestClient(unittest.TestCase):
def test_mqtt_connect(self):
log = logging.getLogger("test_mqtt_connect")
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
log.debug("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
#client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
log.debug(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("gatewaymqtt ", 21883, 60)
sleep(5)
client.disconnect()
if __name__ == '__main__':
unittest.main()
However, I do not see any incoming connection from the test container?
This is the log of the test container:
======================================================================
ERROR: test_mqtt_connect (__main__.TestClient)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_socketio.py", line 69, in test_mqtt_connect
client.connect("gatewaymqtt ", 21883, 60)
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 937, in connect
return self.reconnect()
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 1071, in reconnect
sock = self._create_socket_connection()
File "/usr/local/lib/python3.7/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "/usr/local/lib/python3.7/socket.py", line 728, in create_connection
raise err
File "/usr/local/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
----------------------------------------------------------------------
Upvotes: 2
Views: 4315
Reputation: 4366
When you connect inside docker network use actual port, not exposed one. You should use 21883
when you connect to docker host and 1883
inside docker network.
...
client.connect("gatewaymqtt ", 1883, 60)
...
Upvotes: 1