Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Docker Compose

How to Set Up MQTT With Home Assistant in Docker Compose

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run Home Assistant Container and Eclipse Mosquitto as separate services in one Docker Compose project, attach both to the same Compose network, and use mosquitto—the broker service name—as Home Assistant’s MQTT hostname. Persist Home Assistant’s /config and Mosquitto’s configuration, data, and log directories. Then add MQTT from Settings > Devices & services, enter the broker credentials, and verify traffic before configuring devices.

This arrangement follows Docker’s multi-container model described in the Docker Compose documentation and Home Assistant’s container installation guidance at Home Assistant installation.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the Compose architecture does

MQTT is a lightweight publish/subscribe protocol: devices publish messages to topics and clients subscribe to the topics they need. Home Assistant acts as an MQTT client, while Mosquitto is the broker that receives and forwards those messages. Home Assistant describes MQTT as a machine-to-machine connectivity protocol running on TCP/IP and designed for extremely lightweight publish/subscribe transport; see the MQTT integration documentation.

The two containers should share a user-defined Docker network. Docker’s internal DNS then resolves the Mosquitto service name, so Home Assistant connects to mosquitto:1883. localhost would mean the Home Assistant container itself, not the broker.

#1 Best Overall
MONIGEAR Network Temperature Humidity Monitor, THERMOMETER, Environmental Sensor, Supports MQTT, BACnet, SNMP, Modbus TCP, PoE Power Supply
  • Supports Multiple Industry-Standard Communication Protocols: Modbus TCP, SNMP, BACnet, and MQTT. Our system is compatible with all these protocols and can deliver data in multiple formats simultaneously. Comprehensive support for SNMP v1/v2/v3 and SNMP Trap v2c/v3 with high security level.
  • Can be integrated to AWS/Azure/Tuya loT cloud directly with low cost. Can be directly integrated into Home Assistant
  • Proactive Alerts – Instant email notifications when thresholds are exceeded (fully customizable triggers). IFTTT Automation – Trigger smart actions (e.g., activate HVAC, log to Google Sheets, or Telegram alerts) via Webhook integration.
  • PoE power supply: Centralized power supply: Simply provide uninterrupted power supply at the PoE switch to ensure power supply to the sensor.
  • Easy to use: A graphical interface configuration tool supporting Windows, Linux, and macOS platforms with online remote upgrade capability for simplified product deployment and maintenance.
  • Home Assistant Container: the automation and dashboard application, with its persistent files mounted at /config.
  • Mosquitto: the MQTT broker, with persistent configuration, message data, and logs.
  • Shared network: allows service-name communication without sending internal traffic through the host.
  • Port 1883: the normal MQTT listener. Publish it on the host only when clients outside the Compose network need it.

Prerequisites and project layout

Install Docker Engine and the Docker Compose plugin on the host. Choose a directory for the project and create the persistent directories before starting either service:

mkdir -p homeassistant mosquitto/config mosquitto/data mosquitto/log

A simple layout is:

ha-mqtt/
  compose.yaml
  homeassistant/
  mosquitto/
    config/
    data/
    log/

The directories are bind mounts, so replacing a container or pulling a newer image does not remove the application state stored on the host. Back up these directories before upgrades or large configuration changes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure Mosquitto with authentication

Create mosquitto/config/mosquitto.conf with a listener, password authentication, persistence, and file logging:

listener 1883
allow_anonymous false
password_file /mosquitto/config/passwordfile
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log

This keeps unauthenticated clients off the broker. Port 1883 is not encrypted, so it is appropriate only on a trusted local network or an isolated Docker network. Add TLS when a broker connection crosses an untrusted network; do not expose an unauthenticated plaintext listener to the internet.

Create the password file interactively so the secret is not placed in shell history:

docker compose run --rm mosquitto mosquitto_passwd -c /mosquitto/config/passwordfile homeassistant

Enter the password when prompted. The file is inside the mounted configuration directory and therefore survives container recreation. Keep it out of public repositories and protect the host directory with normal filesystem permissions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create the Compose file

Save this as compose.yaml in the project directory:

Rank #2
Ethernet Server Room Temperature Monitor (Swiss Sensors) PoE Server Rack Temperature Humidity Sensor with Web Interface, SNMP Modbus MQTT Support, Dual Power, IP55, Data Logging, Alarm & Relay Output
  • Precision Monitoring for Critical Environments: The server room temperature monitor is a professional temperature and humidity monitor built for continuous reliability in data centers, network closets, and industrial environments. Featuring a Swiss-grade external probe with ±0.2 °C and ±2 %RH typical accuracy, it delivers precise real-time measurements of temperature, humidity, and dew point — ensuring sensitive equipment stays within safe operating conditions.
  • Real-Time Local Display and Easy Setup: With its bright 3.5-inch TFT color screen, this server room temperature monitor lets users instantly view live values and alarm status directly on the device — no PC required. Configure thresholds, network settings, and relay actions using simple front-panel buttons or through the integrated web interface. Perfect for on-site checks in IT rooms, labs, cold storage, or pharmaceutical facilities.
  • Multi-Channel Smart Alerts & Automated Response: Stay protected from sudden changes with multi-channel notifications. The server rack temperature monitor supports email alerts via SMTP, SNMP trap, and MQTT messages, as well as visual and audible alarms. Use the onboard relay output to automatically activate fans, AC units, dehumidifiers, or warning lights — enabling true automated environmental control for your server room or warehouse.
  • Powerful Network Integration & Open Protocols: Engineered for seamless system compatibility, this PoE server room temperature monitor supports Ethernet 10/100M, Modbus TCP, SNMP v1/v2, UDP, MQTT, DHCP, and RS-485 to Ethernet bridging. It easily connects with BMS, SCADA, DCIM, or custom IoT dashboards for centralized visibility. View and adjust MAC address, IP, and protocol settings directly from its browser-based interface.
  • Local Data Logging & No Subscription Fees: Unlike cloud-dependent devices, the server room temperature monitor stores up to 100,000 records locally with a customizable sampling interval as low as 2 minutes. Historical logs can be exported in CSV format for compliance, audits, or trend analysis. Data stays secure on-site — no monthly fees, no forced cloud account, and no risk of lost records during network downtime.
services:
  mosquitto:
    image: eclipse-mosquitto:2
    container_name: mosquitto
    restart: unless-stopped
    volumes:
      - ./mosquitto/config:/mosquitto/config
      - ./mosquitto/data:/mosquitto/data
      - ./mosquitto/log:/mosquitto/log
    ports:
      - '1883:1883'
    networks:
      - ha_net

  homeassistant:
    image: ghcr.io/home-assistant/home-assistant:stable
    container_name: homeassistant
    restart: unless-stopped
    depends_on:
      - mosquitto
    volumes:
      - ./homeassistant:/config
      - /etc/localtime:/etc/localtime:ro
    ports:
      - '8123:8123'
    networks:
      - ha_net

networks:
  ha_net:
    driver: bridge

The depends_on entry starts Mosquitto before Home Assistant, but it does not prove that the broker is ready to accept connections. Home Assistant may retry while Mosquitto finishes starting.

Choose the right port exposure

The example publishes both the Home Assistant web port and MQTT port on the Docker host. If only containers need MQTT, remove the Mosquitto ports section; Home Assistant will still reach it at mosquitto:1883 over ha_net. If host-only tools need MQTT, bind the port to the host loopback interface instead:

ports:
  - '127.0.0.1:1883:1883'

If another process already uses host port 1883, you can publish a different host port such as 1884:1883. The internal Home Assistant setting remains port 1883; only clients connecting through the host use 1884.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start the containers and open Home Assistant

  1. From the directory containing compose.yaml, validate the rendered configuration:
    docker compose config
  2. Start both services in the background:
    docker compose up -d
  3. Check service state and recent logs:
    docker compose ps
    docker compose logs --tail=100 mosquitto
    docker compose logs --tail=100 homeassistant
  4. Open http://HOST:8123, replacing HOST with the Docker host name or address, and complete Home Assistant’s first-run account setup.

Do not delete the homeassistant directory when recreating containers: it contains Home Assistant’s configuration and database. Likewise, Mosquitto’s data and password file are in the mounted mosquitto directories.

Add the MQTT integration in Home Assistant

  1. Open Settings > Devices & services.
  2. Select Add Integration and search for MQTT.
  3. For the broker host, enter mosquitto, not localhost and not the host machine’s address.
  4. Enter port 1883, the username created in passwordfile, and its password.
  5. Submit the form and confirm that the MQTT integration appears as configured.

Home Assistant requires a broker that supports MQTT protocol version 5. The official Mosquitto broker supports MQTT 5. Home Assistant’s keep-alive default is 60 seconds; if a client setting is exposed, keep it at 15 seconds or higher.

For an external broker, use that broker’s DNS name or IP address, its listening port, and its authentication or TLS settings instead. The service name mosquitto works only for the Mosquitto service on the shared Compose network.

Verify publish and subscribe before adding devices

Testing first separates broker and network problems from device or discovery problems. With port 1883 published on the host and authentication enabled, run a subscriber in one terminal:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
MONIGEAR WiFi Temperature Humidity Monitor, Thermometer, Environmental Sensor, Supports MQTT, BACnet, SNMP, Modbus TCP, Home Assistant Ready, Email/IFTTT
  • Supports Multiple Industry-Standard Communication Protocols: Modbus TCP, SNMP, BACnet, and MQTT. Our system is compatible with all these protocols and can deliver data in multiple formats simultaneously. Comprehensive support for SNMP v1/v2/v3 and SNMP Trap v2c/v3 with high security level.
  • A web service can be enabled to view sensor data directly through a browser. Support for the REST API protocol can also be enabled to return JSON data from the sensors. However, these two features are disabled by default for network security reasons, and can be enabled by configuration tool.
  • Can be integrated to AWS/Azure/Tuya loT cloud directly with low cost. Can be directly integrated into Home Assistant.
  • Wifi network. Provides reliable Wi-Fi connectivity with native support for WPA-Enterprise and 802.1X authentication, enabling seamless integration into enterprise-grade security architectures.
  • Proactive Alerts – Instant email notifications when thresholds are exceeded (fully customizable triggers). IFTTT Automation – Trigger smart actions (e.g., activate HVAC, log to Google Sheets, or Telegram alerts) via Webhook integration.
mosquitto_sub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -v -t 'homeassistant/#'

In a second terminal, publish a test message:

mosquitto_pub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -t 'homeassistant/switch/1/on' -m 'Switch is ON'

The subscriber should print the topic and payload. Home Assistant’s documentation shows the same basic mosquitto_pub and mosquitto_sub pattern at the MQTT integration page; the username and password above are required because this configuration disables anonymous access.

To test entirely inside Docker when the host port is not published, run the clients from the Mosquitto container:

docker compose exec mosquitto mosquitto_sub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -v -t 'homeassistant/#'
docker compose exec mosquitto mosquitto_pub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -t 'homeassistant/test' -m 'hello'

Home Assistant also exposes Configure controls for the MQTT integration. Use its publish control to send a packet and its listen control to subscribe to a topic when command-line clients are unavailable.

Use MQTT discovery to create entities

MQTT discovery is enabled by default. Its default topic prefix is homeassistant. A device first publishes a configuration payload to a discovery topic. Home Assistant then uses the state and command topics named in that payload.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Switch topic pattern

A documented switch pattern is:

  • Discovery configuration: homeassistant/switch/irrigation/config
  • State: homeassistant/switch/irrigation/state
  • Command: homeassistant/switch/irrigation/set

An example configuration payload is:

{"name":"Irrigation","unique_id":"irrigation_switch_1","command_topic":"homeassistant/switch/irrigation/set","state_topic":"homeassistant/switch/irrigation/state","payload_on":"ON","payload_off":"OFF"}

Publish the configuration as a retained message so Home Assistant can reconstruct the entity after a restart:

mosquitto_pub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -r -t 'homeassistant/switch/irrigation/config' -m '{"name":"Irrigation","unique_id":"irrigation_switch_1","command_topic":"homeassistant/switch/irrigation/set","state_topic":"homeassistant/switch/irrigation/state","payload_on":"ON","payload_off":"OFF"}'

The device should publish its state on the state topic and listen for commands on the command topic. Topic names and payload values must match the configuration exactly.

Handle Home Assistant restarts

Retained discovery configuration is the simplest recovery method. Another approach is for a device or automation to subscribe to homeassistant/status and republish its discovery configuration when Home Assistant announces online. This is useful when a device deliberately does not retain its configuration.

Rank #4
MONIGEAR Indoor Air Quality Monitor, 4-in-1 Temperature Humidity CO2 TVOC Sensor, AWS/Azure/Tuya IoT with PoE, LCD Display, Protocol: MQTT, BACnet, SNMP, Modbus TCP, Home Assistant Ready, Email/IFTTT
  • 4-in-1 Environmental Monitor (TVOC, CO₂,Temperature,Humidity). High accuracy:Temperature measurement accuracy: ± 0.3° C; Humidity measurement accuracy: ±3%;CO₂ measuring range: 0-2000ppm.
  • Supports Multiple Industry-Standard Communication Protocols: Modbus TCP, SNMP, BACnet, and MQTT. Our system is compatible with all these protocols and can deliver data in multiple formats simultaneously. Comprehensive support for SNMP v1/v2/v3 and SNMP Trap v2c/v3 with high security level.
  • Can be integrated to AWS/Azure/Tuya loT cloud directly with low cost. Can be directly integrated into Home Assistant
  • Proactive Alerts – Instant email notifications when thresholds are exceeded (fully customizable triggers). IFTTT Automation – Trigger smart actions (e.g., activate HVAC, log to Google Sheets, or Telegram alerts) via Webhook integration.
  • PoE power supply: Centralized power supply: Simply provide uninterrupted power supply at the PoE switch to ensure power supply to the sensor.

To observe the birth message while diagnosing startup behavior:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mosquitto_sub -h 127.0.0.1 -p 1883 -u homeassistant -P 'your-password' -t 'homeassistant/status' -v

Discovery configuration is separate from live state. Ensure the device publishes current state after reconnecting so the entity reflects reality rather than only the last command.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Security, credentials, and ongoing operations

Authentication and reserved usernames

The password-file method above is the normal approach for a standalone Mosquitto container. The Home Assistant Mosquitto broker app has a different management interface: its documentation describes creating MQTT users through Settings > People > Users, and reserves the usernames homeassistant and addons in that app context. Do not assume those app controls edit the password file of an independently deployed Compose container.

Save broker credentials and app options before reinstalling or rebuilding. Home Assistant’s MQTT documentation warns that generated credentials are kept secret; losing them can require recreating the account and updating every client.

Network exposure and TLS

Port 1883 carries plaintext MQTT. Keep it on the private Compose network when possible, bind published access to loopback for local administration, and use firewall rules if other LAN clients must connect. For traffic over an untrusted network, configure Mosquitto with certificates and a TLS listener, then select the corresponding secure port and certificate options in Home Assistant. Do not treat a published Docker port as encrypted merely because the containers share a bridge network.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Persistence and backups

  • Back up homeassistant/ for Home Assistant configuration and its recorder database.
  • Back up mosquitto/config/, including passwordfile and mosquitto.conf.
  • Back up mosquitto/data/ if retained MQTT messages and broker persistence matter to your deployment.
  • Include mosquitto/log/ when diagnosing failures, but rotate or prune logs so they do not consume the disk.

Stop or quiesce the services before a filesystem-level backup when consistency matters, and test that a backup can be restored to a separate directory.

Updates and ownership

Compose gives you a repeatable way to start, stop, and replace containers, but you still own image updates, configuration backups, credential rotation, and host security. Review logs after an image update and verify the MQTT test message before reconnecting all devices.

Best Value
Sale
GoveeLife 2.0 WiFi Hygrometer Thermometer with Gateway, Mini Sensor 3-Pack
  • Smart WiFi Control: Monitor indoor thermometer data anytime, anywhere. The gateway can be connected through WiFi via the app, pairing up to 10 humidity temperature sensors. Boasts a 2-year battery life (Supports 2.4GHz Wifi networks only)
  • High-Precision Readings: The Swiss-made WiFi temperature sensor provides precise readings, measuring temperatures with ±0.54°F / ±0.3℃ accuracy and humidity within ±3% RH. Data is refreshed every 2s, ideal for wine cellars.
  • Remote Alarm: You can preset temperature and humidity values ​​via the app. When the hygrometer thermometer sensor detects a change, you'll receive a notification via app and email, offering enough time to react through the alarm function.Only support gateway H5151/H5042.
  • Data Storage & Export: This humidity monitor uploads data to the app via WiFi and Bluetooth. View the temperature and humidity trend chart from the past 20 days and export data from the past 2 years. Ideal for greenhouses, farms, etc.
  • Compact & Portable Design: This indoor thermometer adopts a compact and stylish design equipped with a lanyard, suitable for any corner of the room, such as drawers, wine cabinets, guitar cases, etc.

Choose between a Compose broker and an external broker

Decision axis Mosquitto in the same Compose project Broker on another host
Broker address mosquitto on the shared Docker network External DNS name or IP address; exact value depends on that host
Network exposure Can remain internal by omitting the MQTT ports mapping Requires network routing and an exposed broker listener
Authentication and TLS Configured in the Mosquitto container and its mounted files Configured and operated by whoever owns the external broker
Persistence and backup Back up the Compose bind-mounted directories Follow the external host’s storage and backup policy
Discovery behavior Uses the default homeassistant prefix unless changed Home Assistant discovery is the same, but network reachability is an additional dependency
Operational ownership You update both containers and the Docker host You operate Home Assistant while another system may operate the broker

There is no universal performance or cost advantage established for either arrangement. Choose the same-project option when you want a self-contained deployment and can maintain both services; choose an external broker when an existing, separately managed MQTT service is already required.

Troubleshoot the common failures

Home Assistant cannot connect to the broker

  • Confirm both services are running with docker compose ps.
  • Use mosquitto as the hostname and 1883 as the internal port. Do not use localhost from Home Assistant.
  • Check that both services list ha_net in the Compose file and recreate them after network changes with docker compose up -d.
  • Read Mosquitto’s log for listener, password-file, or permission errors.

Connection refused from a host test

Verify that the MQTT ports mapping exists and that the host-side port is not already occupied. If you changed the mapping to 1884:1883, use port 1884 from the host; Home Assistant still uses 1883 internally.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authentication fails

Check the username and password against the account in /mosquitto/config/passwordfile. Recreate or change the account with mosquitto_passwd, then restart Mosquitto:

docker compose restart mosquitto

Do not add an anonymous fallback just to make a test pass; that hides the real credential problem and weakens the broker.

The integration reports an unsupported protocol

Use a broker with MQTT version 5 support. Mosquitto is the documented compatible choice for Home Assistant. Check the image and broker logs if a different broker or an old client is negotiating an incompatible protocol.

Discovery entities do not appear

  • Confirm the configuration topic uses the homeassistant prefix and ends in /config.
  • Validate that the payload is valid JSON and names the state and command topics correctly.
  • Subscribe to homeassistant/# to see whether the configuration message is arriving.
  • Retain the configuration message, or republish it when homeassistant/status announces online.
  • Check that the device’s unique_id is stable; changing it creates a different entity rather than updating the old one.

Data disappears after a rebuild

Inspect the bind mounts with docker compose config and confirm that the host directories are the ones being mounted. Recreating a container is safe only when its configuration and data live outside the container filesystem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational checklist

  • Home Assistant and Mosquitto run as separate services on one shared Compose network.
  • Home Assistant connects to mosquitto:1883, never to its own localhost.
  • Anonymous access is disabled and credentials are stored in the persistent password file.
  • MQTT port 1883 is published only when a host or LAN client needs it.
  • Home Assistant’s /config and Mosquitto’s config, data, and log directories are backed up.
  • The MQTT integration is added through Settings > Devices & services.
  • A publish/subscribe test succeeds before device troubleshooting begins.
  • Discovery configuration is retained or republished after Home Assistant’s online birth message.
  • TLS is used whenever MQTT crosses an untrusted network.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Docker ComposeHome AssistantHome AutomationMosquittoMQTT

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.