求助:MQTT使用公网IP无法正常工作问题排查
Hey there, let’s work through this Mosquitto public IP connectivity problem step by step. First, let’s recap your setup to make sure we’re aligned:
Your Setup Details
- Public Server IP: 1.2.3.4
- Operating System: Raspbian Stretch (Debian 9)
- Running Services: Apache2 (hosting 2 websites), Mosquitto MQTT broker
- Mosquitto Credentials: Username
user, Passwordpsw
You mentioned local testing works flawlessly with these commands:
mosquitto_pub -h localhost -p 1883 -t topic -u "user" -P "psw" -m "new message"
mosquitto_sub -h localhost -p 1883 -t topic -u "user" -P "psw"
And you can receive the "new message" without hiccups. But when trying to connect via your public IP, you’re hitting roadblocks—let’s break down the most common fixes for this:
Key Troubleshooting Steps
1. Ensure Mosquitto Listens on All Interfaces
By default, Mosquitto often only binds to the localhost interface (127.0.0.1), meaning it won’t accept external connections. Here’s how to fix that:
- Open your Mosquitto config file (usually at
/etc/mosquitto/mosquitto.confor/etc/mosquitto/conf.d/default.conf) - Look for the
listenerdirective. If it’s set to1883 127.0.0.1, update it to:
This tells Mosquitto to listen on all network interfaces.listener 1883 0.0.0.0 - Restart the service to apply changes:
sudo systemctl restart mosquitto
2. Open Port 1883 in Your Firewall
Your Raspbian server’s firewall (likely ufw) is probably blocking incoming traffic on port 1883:
- Check current firewall rules:
sudo ufw status - If
1883/tcpisn’t listed as allowed, add it:sudo ufw allow 1883/tcp - Reload the firewall to confirm changes:
sudo ufw reload
3. Set Up Port Forwarding on Your Router
If your server is behind a home router, you need to forward external port 1883 to your Raspberry Pi’s local IP:
- Log into your router’s admin panel (typically via
192.168.1.1or similar) - Navigate to the "Port Forwarding" or "Virtual Server" section
- Create a rule:
- External Port: 1883
- Internal Port: 1883
- Internal IP: Your Pi’s local network address (e.g.,
192.168.1.100) - Protocol: TCP
- Save the rule and restart the router if needed.
4. Test from a Remote Machine
After making these changes, test from a device outside your local network using:
mosquitto_pub -h 1.2.3.4 -p 1883 -t topic -u "user" -P "psw" -m "public test message"
mosquitto_sub -h 1.2.3.4 -p 1883 -t topic -u "user" -P "psw"
5. Bonus Checks (If Issues Persist)
- Static Public IP: If your public IP changes dynamically, use a dynamic DNS (DDNS) service to keep track of it.
- ISP Restrictions: Some ISPs block port 1883. If this happens, switch Mosquitto to listen on port 8883 (the standard MQTT TLS port) and update your firewall/port forwarding rules.
- Enable TLS: For security, configure Mosquitto to use TLS encryption for public connections by setting up a listener on port 8883 and adding your SSL certificates.
内容的提问来源于stack exchange,提问作者Timmy

