Python service, working with MQTT broker, how to forward host and port in docker?

152 Views Asked by At

The service is written in Python. It works with MQTT queue. When launching the container it fails to connect to the broker. How to cast host and port from outside to the docker. client.connect('127.0.0.1', 61613, 60) Here is the error:

Traceback (most recent call last):
File "//clean.py", line 67, in
client.connect('127.0.0.0.1', 61613, 60)
File "/usr/local/lib/python3.11/site-packages/paho/mqtt/client.py", line 914, in connect
return self.reconnect()
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/paho/mqtt/client.py", line 1044, in reconnect
sock = self._create_socket_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/paho/mqtt/client.py", line 3685, in       _create_socket_connection
return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/socket.py", line 851, in create_connection
raise exceptions[0]
File "/usr/local/lib/python3.11/socket.py", line 836, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

Dockerfile:

FROM python:3.11

ADD clean.py .

ADD requirements.txt .

EXPOSE 61613

RUN pip install -r requirements.txt

CMD ["python", "clean.py"]
1

There are 1 best solutions below

0
CaptainTrunky On

There are two options for this:

  1. Provide environment variable for host/port addresses during a container launch. Read data from these variables using something like os.environ inside your script.
  2. Use docker-compose for running your script in one container and MQTT in another one. Using docker-compose you could setup network alias name and use it to access MQTT from your software