I’m trying to run a chat-webapp using the MQTT protocol on the Docker, but I’m having trouble setting up the SSL communication between the client and Mosquitto mqtt-broker on the Docker.
Here is my docker-compose.yml:
Port 9443 of the host machine is connected to port 9443 of the Docker coontainer for setting up SSL communication. In the volume, we have the path of the SSL certificates.
services:
mqtt-broker:
image: eclipse-mosquitto:latest
container_name: mqtt-broker
ports:
- "1883:1883" # MQTT without SSL
- "8883:8883" # MQTT with SSL
- "9001:9001" # WebSocket without SSL
- "9443:9443" # WebSocket with SSL
volumes:
- ./mqtt/mosquitto.conf:/mosquitto/config/mosquitto.conf
- ./mqtt/certs:/mosquitto/certs # Mount the SSL certificates
user1:
build: ./user1
container_name: user1-web
ports:
- "8081:80"
Here is my mosquitto.conf:
# MQTT without SSL
listener 1883
protocol mqtt
# MQTT with SSL
listener 8883
protocol mqtt
cafile /mosquitto/certs/ca.crt
certfile /mosquitto/certs/mosquitto.crt
keyfile /mosquitto/certs/mosquitto.key
require_certificate false
# WebSocket without SSL
listener 9001
protocol websockets
# WebSocket with SSL
listener 9443
protocol websockets
cafile /mosquitto/certs/ca.crt
certfile /mosquitto/certs/mosquitto.crt
keyfile /mosquitto/certs/mosquitto.key
Here is the html file as a client:
<!DOCTYPE html>
<html>
<head>
<title>User 1 Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mqtt/4.2.8/mqtt.min.js"></script>
<script>
var client = mqtt.connect('wss://localhost:9443');
client.on('connect', function () {
client.subscribe('chat');
document.getElementById('status').textContent = 'Connected';
});
client.on('message', function (topic, message) {
var chatArea = document.getElementById('chat');
var newMessage = document.createElement('div');
newMessage.textContent = message.toString();
chatArea.appendChild(newMessage);
});
function sendMessage() {
var message = document.getElementById('message').value;
client.publish('chat', 'User 1: ' + message);
document.getElementById('message').value = '';
}
</script>
</head>
<body>
<h1>User 1 Chat</h1>
<div id="status">Not Connected</div>
<div id="chat" style="border: 1px solid #000; height: 300px; overflow-y: scroll; padding: 10px;"></div>
<input type="text" id="message">
<button onclick="sendMessage()">Send</button>
</body>
</html>
When I run this on the Docker desktop, I got an error:
"mqtt-broker | 1723506790: Client mqttjs_8ebdd3c7 closed its connection."
It’s difficult for me to check what’s wrong. If anyone can see the mistakes or anyone can execute the file without problem. please, let me know, it means a lot to me.
ming is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.