skip to Main Content

I’m trying to setting up a reverse proxy that resolve localhost:8081 to a broker installed on an other machine.
My Nginx config file is:

worker_processes  1;

events {
    worker_connections 1024;
}

server {
    listen 8081;
    server_name localhost;

    location / {
        proxy_pass tcp://192.168.1.177:1883;
    }
}

But when I try to connect to the broker (from the machine where I’m configuring Nginx) with the command

 mosquitto_sub -h localhost -p 8081 -t "stat/tasmota_8231A8/POWER1"

I get the error Connection refused.

Edit:
Mosquitto broker config:

persistence true
persistence_location /var/lib/mosquitto/

include_dir /etc/mosquitto/conf.d

listener 1883
allow_anonymous true

Edit
I try with this config file for nginx
worker_processes 1;

events {
    worker_connections 1024;
}
stream {
   listen 8081;
   proxy_pass 192.168.1.77:1883;
} 

3

Answers


  1. This won’t work for native MQTT.

    What you have configured is a HTTP proxy, but MQTT != HTTP.

    You need to configure nginx as a stream proxy. e.g.

    stream {
      server {
          listen 8081;
          proxy_pass 192.168.1.77:1883;
      }
    }
    

    https://docs.nginx.com/nginx/admin-guide/tcp-udp-load-balancer/

    Or configure mosquitto to support MQTT over WebSockets (Assuming the client supports this as well). Then you can use HTTP based proxying as WebSockets bootstrap via HTTP.

    Login or Signup to reply.
  2. Connection refused is indicative of trying to connect to a port on which no service is listening. Please verify that nginx service is running and that a listener indeed exists. You can do this by

    sudo netstat -nlt 
    

    This command will show you ports that are taken. The configured port of the nginx listener should appear in the list

    Login or Signup to reply.
  3. I got your scenario fully working with the following config (firewall turned off, SELinux set to permissive):

    nginx config (on loadbalancer1):

    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;
    
    include /usr/share/nginx/modules/*.conf;
    
    events {
       worker_connections 1024;
    }
    
    
    stream {
    
       server {
          listen              1883;
          proxy_pass          stream_backend;
          proxy_buffer_size   16k;
       }
    
    
       upstream stream_backend {
          server mqtt-node-1:1883;
          server mqtt-node-2:1883;
      }
    

    }

    mosquitto config on mqtt-node-1 and mqtt-node-2:

    max_queued_bytes 10000
    
    max_queued_messages 100
    
    listener 1883
    
    log_type error
    log_type information
    log_type debug
    log_type warning
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search