docker-mqtt服务器-eclipse-mosquitto安装
1.拉取docker pull eclipse-mosquittodocker imagesREPOSITORYTAGIMAGE IDCREATEDSIZEeclipse-mosquittolatest4ded7c6229999 days...
·
1.拉取
docker pull eclipse-mosquitto
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
eclipse-mosquitto latest 4ded7c622999 9 days ago 6.28MB
2 建立配置目录
mkdir -p /mosquitto/config
mkdir -p /mosquitto/data
mkdir -p /mosquitto/log
- 建立配置文件
vi /mosquitto/config/mosquitto.conf
# 写入以下内容
persistence true
persistence_location /mosquitto/data
log_dest file /mosquitto/log/mosquitto.log
- 为目录授权
chmod -R 755 /mosquitto
chmode -R 777 /mosquitto/log #日志目录要最大权限
- 建立运行脚本mosquitto.sh
docker run -it --name=mosquitto --privileged -p 1883:1883 -p 9001:9001 -v /mosquitto/config:/mosquitto/config/ -v /mosquitto/data/:/mosquitto/data -v /mosquitto/log/:/mosquitto/log -d eclipse-mosquitto
./mosquitto.sh运行
说明
提示【Error: Unable to open log file /mosquitto/log/mosquitto.log for writing.】
则删了已有的日志文件重新建一个并授权再启动即可。
- 配置权限
vim /mosquitto/config/mosquitto.conf
1)、配置文件添加以下配置
# 关闭匿名模式
allow_anonymous false
# 指定密码文件
password_file /mosquitto/config/pwfile.conf
- 进入容器
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3fdbb2bc353c eclipse-mosquitto "/docker-entrypoint.…" About an hour ago Up About an hour 0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp mosquitto
56571b7ba421 zookeeper "/docker-entrypoint.…" 2 months ago Up 2 hours 0.0.0.0:2181->2181/tcp, 0.0.0.0:2888->2888/tcp, 0.0.0.0:3888->3888/tcp, 8080/tcp zk
docker exec -it 3fdbb2bc353c sh
- 、生成密码
#对于passworf_file,可以复制一份模板,或者创建一个空文件
touch /mosquitto/config/pwfile.conf
chmod -R 755 /mosquitto/config/pwfile.conf
# 使用mosquitto_passwd命令创建用户,第一个test是用户名,第二个test2019是密码
mosquitto_passwd -b /mosquitto/config/pwfile.conf test test2019
- 重启mqtt服务
docker restart 3fdbb2bc353c
使用MQTT.fx进行连接。
连接成功
10 .python 测试下
pip install paho-mqtt
# !/usr/bin/python
# -*-coding:utf-8-*-
# @Author: 刘楠
# @Time: 2019/12/12 17:01
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("lettuce")
def on_message(client, userdata, msg):
print(client,userdata,msg.topic + " " + str(msg.payload))
client = mqtt.Client()
client.username_pw_set("test", "test2019") # 必须设置,否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
HOST = "192.168.230.128"
client.connect(HOST, 1883, 60)
# 向topic1发送100条消息
for i in range(100):
client.publish(topic="topic1",payload="去放醋范德萨范德萨 %s"%i)
client.loop_forever()
收到消息
更多推荐
已为社区贡献2条内容
所有评论(0)