MQTT is a publish/subscribe protocol whose usage is growing a lot in recent years, especially in the field of Internet of Things (IoT) and Wireless Sensor Networks (WSN) applications. The protocol is based on a central broker entity, which is in charge of collecting publications and subscriptions from clients and forwarding messages among them. In this work, we propose a distributed version of the protocol, named D-MQTT, where multiple brokers connect among themselves, allowing clients to communicate even if originally associated to different brokers. Distinctive features of our proposal are: (i) automatic broker discovery, (ii) creation of an optimized, failure-resistant overlay network among the brokers and (iii) efficient routing of the publication messages. We propose an implementation of D-MQTT based on the popular open-source Mosquitto broker and we evaluate its performance on a network of brokers using the Containernet framework, comparing its performance with the standard MQTT bridging distribution approach. The source-code of D-MQTT is made publicly available at https://tinyurl.com/MQTT-Distributed.