2G 小服务器搭 MQTT:Mosquitto 安装、安全配置与 ESP32 连接
想做个小物联网项目:单片机把温湿度上报到服务器,服务器再下发指令。最合适的协议就是 MQTT——轻量、省流量、天然适合弱网设备。
我用一台 2 核 2G 的轻量服务器实测了一遍,从零到 ESP32 能连,全程不到 30 分钟。记录一下。
为什么是 Mosquitto
- 内存占用极小(实测基础约 12MB),2G 小机器毫无压力
- 标准 MQTT 3.1.1/5.0,ESP32、ESP8266、STM32 的库都兼容
- Debian 直接 apt 安装,省心
apt-get install -y mosquitto mosquitto-clients
mosquitto -h | head -2
关键一步:关闭匿名访问
默认配置允许匿名连接,千万别直接暴露到公网。先建账号:
mosquitto_passwd -b -c /etc/mosquitto/passwd iotuser 你的密码
chmod 640 /etc/mosquitto/passwd
chown root:mosquitto /etc/mosquitto/passwd
然后写配置 /etc/mosquitto/conf.d/iot.conf:
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd
max_connections 5000
max_queued_messages 1000
重启并确认:
systemctl restart mosquitto
systemctl enable mosquitto
ss -tlnp | grep 1883
开防火墙
云服务器还要在安全组/防火墙放行 TCP 1883(只放业务端口,别全开)。
验证:先在本机 pub/sub
# 终端 A 订阅
mosquitto_sub -h 127.0.0.1 -u iotuser -P '你的密码' -t 'test/#' -v
# 终端 B 发布
mosquitto_pub -h 127.0.0.1 -u iotuser -P '你的密码' -t 'test/hello' -m 'hello mqtt'
订阅端能看到消息就说明 broker 正常。
再验证一下认证真的生效:
# 匿名连接应该失败
mosquitto_pub -h 127.0.0.1 -t test/x -m x
# Connection Refused: not authorised
ESP32 连接示例(Arduino / PubSubClient)
#include <WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin("你的WiFi", "密码");
while (WiFi.status() != WL_CONNECTED) delay(500);
client.setServer("你的服务器IP", 1883);
if (client.connect("esp32-001", "iotuser", "你的密码")) {
Serial.println("MQTT connected");
client.publish("devices/esp32-001/status", "{\"online\":true}");
}
}
void loop() {
if (!client.connected()) client.connect("esp32-001", "iotuser", "你的密码");
client.loop();
}
Topic 设计建议:
devices/<设备ID>/status 设备上报状态
devices/<设备ID>/cmd 服务端下发指令
devices/<设备ID>/log 设备日志
2G 小服务器能扛多少设备
- 连接数:Mosquitto 每连接约占 10–30KB,2G 内存可承载几千个空闲连接(需要调高系统文件句柄上限)
- 带宽:小消息(几十字节)非常省流量,4Mbps 带宽足够几百台设备低频上报
- 不适合:视频流、大文件、高频大数据上报
上生产前必做的三件事
- 启用 TLS(8883):明文 1883 只适合内网或联调,公网务必加密(可以用 Let's Encrypt 证书)
- 每台设备独立账号 + ACL:设备只能读写自己的 topic,防止相互干扰或恶意监听
- 监控与限流:连接数、消息量、异常登录告警;给设备加遗嘱消息(LWT)判断离线
小结
2 核 2G 跑 MQTT 完全够用,成本极低。真正要花心思的是安全:别用匿名、别只用一个密码走天下、公网记得上 TLS。
需要帮忙搭 MQTT / 设备接入 / 数据上报到微信告警的,可以找我。