title: Docker (Compose) client connects to Kafka too early
body: <p>I am trying to run Kafka with Docker and Docker Compose. This is the <code>docker-compose.yml</code>:</p>
  
  <pre><code>version: "2"
  
  services:
    zookeeper:
      image: "wurstmeister/zookeeper"
      ports:
        - "2181:2181"
  
    kafka:
      build:
        context: "./services/kafka"
        dockerfile: "Dockerfile"
      ports:
        - "9092:9092"
      environment:
        KAFKA_ADVERTISED_HOST_NAME: "0.0.0.0"
        KAFKA_CREATE_TOPICS: "test:1:1"
        KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      volumes:
        - "/var/run/docker.sock:/var/run/docker.sock"
  
    users:
      build:
        context: "./services/users"
        dockerfile: "Dockerfile"
      ports:
        - "4001:4001"
      environment:
        NODE_ENV: "develop"
        ZOOKEEPER_HOST: "zookeeper"
        ZOOKEEPER_PORT: "2181"
      volumes:
        - "./services/users:/service"
  </code></pre>
  
  <p>The users service only tries to connect (using kafka-node in Node.js) and listens on a topic and publishes one message to it every time it is ran.</p>
  
  <p>The problem is that I keep getting Connection Refused errors. I am using Dockerize to wait for the kafka port to be available in the <code>Dockerfile</code> with the line <code>CMD dockerize -wait tcp://kafka:9092 node /service/index.js</code>.</p>
  
  <p>It waits for the port to be available before starting the users container and this system works, but it is not at the right time. It seems that Kafka is opening the 9092 port before it has elected a leader.</p>
  
  <p>When I run Kafka first and let it start completely and then run my app, it runs smoothly.</p>
  
  <p>How do I wait for the correct moment before starting my service?</p>