1、查询镜像
docker search mosquitto
2、拉取镜像
docker pull eclipse-mosquitto
3、查看镜像
docker images eclipse-mosquitto
4、创建目录文件
4.1创建目录
此目录是关键,不能使用其他目录
mkdir -p /mosquitto/config
mkdir -p /mosquitto/data
mkdir -p /mosquitto/log
4.2初始化配置文件
vi /mosquitto/config/mosquitto.conf
# 输入一下命令内容
persistence true
persistence_location /mosquitto/data
log_dest file /mosquitto/log/mosquitto.log
#高版本需要添加,否则不能远程
listener 1883
可以在日志看到,若没有增加listener 配置的话,只是local模式,
1635411945: Starting in local only mode. Connections will only be possible from clients running on this machine.
1635411945: Create a configuration file which defines a listener to allow remote access.
4.3为目录授权
chmod -R 755 /mosquitto
chmod -R 777 /mosquitto/log #日志目录要最大权限
5、启动镜像
建立运行执行脚本 mosquitto.sh
docker run -it --name=mosquitto --privileged
-p 1883:1883 -p 9001:9001
-v /mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf
-v /mosquitto/data:/mosquitto/data
-v /mosquitto/log:/mosquitto/log
-d eclipse-mosquitto
sudo docker run -it --name=mosquitto --privileged -p 1883:1883 -p 9001:9001 -v /usr/local/mosquitto/config/mosquitto.conf:/usr/local/mosquitto/config/mosquitto.conf -v /usr/local/mosquitto/data:/usr/local/mosquitto/data -v /usr/local/mosquitto/log:/usr/local/mosquitto/log -d eclipse-mosquitto
Authentication methods | Eclipse Mosquitto
docker run -it --name=mosquitto --privileged -p 1883:1883 -p 9001:9001 -v /mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf -v /mosquitto/data:/mosquitto/data -v /mosquitto/log:/mosquitto/log -d eclipse-mosquitto
注意:
如果提示【Error: Unable to open log file /mosquitto/log/mosquitto.log for writing.】
则删了已有的日志文件重新建一个并授权再启动即可。
6、查看容器运行情况
7、配置权限
vim /mosquitto/config/mosquitto.conf
配置文件添加以下配置
# 关闭匿名模式
allow_anonymous false
# 指定密码文件
password_file /mosquitto/config/pwfile.conf
8、进入容器
docker exec -it 06e57924bf31 sh
9、生成密码
#对于passworf_file,可以复制一份模板,或者创建一个空文件
touch /mosquitto/config/pwfile.conf
chmod -R 755 /mosquitto/config/pwfile.conf
# 使用mosquitto_passwd命令创建用户,第一个test是用户名,第二个test2020是密码
mosquitto_passwd -b /mosquitto/config/pwfile.conf test test2020
10、重启mqtt服务
docker restart 06e57924bf31
11、使用MQTT.fx进行连接。