LoginSignup
3
4

More than 3 years have passed since last update.

DockerでMosquittoを動かしてMQTTとWebSocket通信してみる

Posted at

DockerfileとMosquittoの設定ファイルを作ります。

Dockerfile
FROM ubuntu:18.04

RUN apt-get update
RUN apt-get install -y mosquitto mosquitto-clients

COPY ./mosquitto.conf /etc/mosquitto/mosquitto.conf

# MQTT Port
EXPOSE 1883

# WebSocket Port
EXPOSE 8080

CMD ["mosquitto", "-c", "/etc/mosquitto/mosquitto.conf"]
mosquitto.conf
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d

listener 1883

listener 8080
protocol websockets

イメージをビルド、コンテナを起動します。

$ docker build -t mosquitto_image .
$ docker run -d -p 1883:1883 -p 8080:8080 --name mosquitto_container mosquitto_image

MQTTクライアントからpub/subしてみます。

$ mosquitto_pub -h localhost -p 1883 -d -t hello_topic -m "hello"
Client mosq-8zgvruDJ1gCOBNFchP sending CONNECT
Client mosq-8zgvruDJ1gCOBNFchP received CONNACK (0)
Client mosq-8zgvruDJ1gCOBNFchP sending PUBLISH (d0, q0, r0, m1, 'hello_topic', ... (5 bytes))
Client mosq-8zgvruDJ1gCOBNFchP sending DISCONNECT

$ mosquitto_sub -h localhost -p 1883 -d -t hello_topic
Client mosq-GP0NmJL6vHdSMuuhF7 sending CONNECT
Client mosq-GP0NmJL6vHdSMuuhF7 received CONNACK (0)
Client mosq-GP0NmJL6vHdSMuuhF7 sending SUBSCRIBE (Mid: 1, Topic: hello_topic, QoS: 0, Options: 0x00)
Client mosq-GP0NmJL6vHdSMuuhF7 received SUBACK
Subscribed (mid: 1): 0
Client mosq-GP0NmJL6vHdSMuuhF7 received PUBLISH (d0, q0, r0, m0, 'hello_topic', ... (5 bytes))
hello

MQTT over WebSocketからもpub/subしてみます。

image.png

以上。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4