Ubuntu - 22.04 - Server - MQTT ブローカ(JavaScript)


クラウディア 


1. 概要
2. 準備
3. インストール
4. ブローカ構築
5. サービス化
6. 参考サイト

1. 概要

 前ページでは、「apt」コマンドにより、「mosquitto」をインストールしました。  一度、「GitHUB」より「mosquitto」を取得してビルドしてインストールできるかやってみましたが、失敗しました。  「JavaScript」に「MQTT」のブロッカーがあるようなので、それがインストールできるかやってみます。

2. node.js

 「node.js」「npm」が必要なのですが・・・。  当初。

apt install -y npm
 で、取得しようとしたのですが、バージョンが古い。
Node.js — Node.js®をダウンロードする
 から、最新「LTS」、「Linux」版「tar」をダウンロードして、展開します。  「root」ユーザ権限で。

curl https://nodejs.org/dist/v24.11.1/node-v24.11.1-linux-x64.tar.xz --output /tmp/node-v24.11.1-linux-x64.tar.xz

cd /tmp

tar -xvf node-v24.11.1-linux-x64.tar.xz

mv node-v24.11.1-linux-x64 /usr/local/node
 各ユーザで。

echo 'export PATH=/usr/local/node/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
 これで、「node」「npm」が使えるようになります。

$ node --version
v24.11.1
$ npm --version
11.6.2

3. インストール

 ドキュメント管理者権限で、ドキュメントルートへ移動して。

npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See 'npm help init' for definitive documentation on these fields
and exactly what they do.

Use 'npm install <pkg>' afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (mqtt)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
type: (commonjs)
About to write to /path/package.json:

{
  "name": "mqtt",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "type": "commonjs"
}


Is this OK? (yes)
 上記で、プロンプトにはすべて Enter で答えています。  本体をインストール。

npm install aedes ws

added 51 packages, and audited 52 packages in 13s

7 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

vi package.json

{
  "name": "mqtt",
  "version": "1.0.0",
  "description": "",
  "license": "ISC",
  "author": "",
  "type": "commonjs",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "aedes": "^0.51.3",
    "ws": "^8.18.3"
  }
}
 7行目を下記へ書き換えます。

  "type": "module",

4. ブローカ構築

 ドキュメントルートで、ドキュメントの管理者ユーザで。

vi mqtt-broker.js
 下記を記述します。

// mqtt-broker.js
import aedes from 'aedes';
import net from 'net';

const broker = aedes();
const server = net.createServer(broker.handle);
const port = 1883;

server.listen(port, function () {
  console.log('🚀 Aedes MQTT broker started on port', port);
});

broker.on('clientReady', (client) => {
  console.log('✅ クライアント接続:', client.id);
});

broker.on('publish', (packet, client) => {
  if (client) {
    console.log('📨 ${client.id} → ${packet.topic}: ${packet.payload.toString()}');
  }
});
 起動してみます。

node mqtt-broker.js

🚀 Aedes MQTT broker started on port 1883
 別のマシンで、端末を2台開きます。  1台で。

mosquitto_sub -h ip -t test/topic -u "myuser" -P "mypassword"
 もう1台で。

mosquitto_pub -h ip -t test/topic -m "message send" -u "myuser" -P "mypassword"
 いずれも「ip」の箇所に、「node」を起動しているマシンのアドレスを記述します。  1台目のマシンに。

message send
 と表示され。  「node」を起動しているマシンに、およそ下記のようなメッセージが表示されれば。

✅ クライアント接続: aedes_qD9j/IQhTHCXLecGWijF1g/0
✅ クライアント接続: aedes_qD9j/IQhTHCXLecGWijF1g/1
📨 aedes_qD9j/IQhTHCXLecGWijF1g/1 → test/topic: message send
 疎通テストは完了です。

5. サービス化

 サービス化の前に、「mqtt-broker.js」のソースのログの部分は、いったんコメントアウトしておきます。  「root」ユーザ権限で。

vi /etc/systemd/system/mqtt-broker.service
 下記を記述します。  (「path」の箇所にはドキュメントルートを記述します。)

[Unit]
Description=Node.js MQTT Broker (Aedes)
After=network.target

[Service]
ExecStart=/usr/local/node/bin/node /path/mqtt-broker.js
WorkingDirectory=/path

# User/Group を指定しなければ root で起動
# User=root
# Group=root

Restart=always
RestartSec=5
Environment=NODE_ENV=production
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
 作成したものを、読み直し・有効化・起動します。

systemctl daemon-reload

systemctl enable mqtt-broker

systemctl start mqtt-broker
 起動を確認します。

systemctl status mqtt-broker
 およそ下記のように表示されれば、サービスは起動しています。

● mqtt-broker.service - Node.js MQTT Broker (Aedes)
     Loaded: loaded (/etc/systemd/system/mqtt-broker.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2025-11-17 06:13:15 UTC; 5s ago
   Main PID: 1475 (MainThread)
      Tasks: 7 (limit: 4558)
     Memory: 64.7M
        CPU: 810ms
     CGroup: /system.slice/mqtt-broker.service
             mq1475 /usr/local/node/bin/node /path/mqtt-broker.js
 前項と同様、疎通テストを行います。

6. 参考サイト

 本ページは、下記のサイトおよび「ChatGPT」くんを参考にさせていただきました。
Node.js 公式サイトからダウンロードしたアーカイブファイル(*.tar.xz)で、UbuntuにNode.jsをインストールする手順

EaseUS
AbemaTV 無料体験