目录
一、拉取镜像
docker pull eclipse-mosquitto:2.0.15-openssl
二、配置
1、创建目录
# 配置文件目录
mkdir -p /mosquitto/config
# 持久化数据目录
mkdir -p /mosquitto/data
# 日志目录
mkdir -p /mosquitto/log
# 注意事项 文件夹授权
chmod -R 755 /mosquitto
2、配置文件:mosquitto.conf
# 修改配置文件
# vi /mosquitto/config/mosquitto.conf
# 开启持久化
persistence true
# 持久化目录
persistence_location /mosquitto/data
# 日志输出文件
log_dest file /mosquitto/log/mosquitto.log
# 监听端口
listener 1883
# 允许匿名访问
allow_anonymous true
# 认证账号密码存储配置文件
password_file /mosquitto/config/pwfile.conf
# 权限划分
acl_file /mosquitto/config/aclfile.conf
3、配置文件:pwfile.conf
touch /mosquitto/config/pwfile.conf
chmod -R 755 /mosquitto/config/pwfile.conf
4、配置文件:aclfile.conf
touch /mosquitto/config/aclfile.conf
chmod -R 755 /mosquitto/config/aclfile.conf
5、启动容器
docker run -it --name=mosquitto -p 1883:1883 -v /mosquitto/config:/mosquitto/config -v /mosquitto/data:/mosquitto/data -v /mosquitto/log:/mosquitto/log -d eclipse-mosquitto::2.0.15-openssl
6、添加用户并授权
# pwfile.conf
# 生成账号/密码
mosquitto_passwd -b /mosquitto/config/pwfile.conf test test
# vi aclfile.conf
# 最前无用户为匿名
topic anonymous/topic/#
user test
topic readwrite test/topic/+/pub
topic readwrite test/topic/type/#
7、注意事项
# 修改完成配置文件后重启容器
docker restart [imageID]
三、mosquitto语法
# aclfile.conf 配置文件语法
# 用户
user <username>
# topic
topic [read|write|readwrite|deny] <topic>
# 正则
pattern [read|write|readwrite|deny] <topic>
# 创建用户
mosquitto_passwd -b [/path/to/pwfile.conf] [username] [password]
四、验证
1、用户验证
# 进入容器内验证
dokcer exec -it [imageId] /bin/sh
# 订阅消息
/ # mosquitto_sub -u test -P test -t test/topic/123/pub
# 发送消息
/ # mosquitto_pub -u test -P test -t test/topic/123/pub -m "{'aa':'bb'}"
# 此时在订阅消息下会显示
/ # mosquitto_sub -u test -P test -t test/topic/123/pub
{'aa':'bb'}
2、匿名验证
# 订阅消息
/ # mosquitto_sub -t anonymous/topic/123
# 发布消息
/ # mosquitto_pub -t anonymous/topic/123 -m "{'aa':'bb'}"
# 订阅收到消息
/ # mosquitto_sub -t anonymous/topic/123
{'aa':'bb'}
3、注意
# aclfile.conf
# 权限生产消息成功但消费不到数据
topic anonymous/topic/#
# 读写消息
topic readwrite anonymous/topic/#