Kafka String Message is throwing Exception when sending a message with key=’null’

I am trying to send String message using Kafka, its throwing Exception with Key of the message being null. But as far as I know the key is automatically assigned by Kafka.

I am getting this error in my console.

2021-02-23 14:34:10.420 ERROR 36996 --- [ad | producer-1] o.s.k.support.LoggingProducerListener    : Exception thrown when sending a message with key='null' and payload='"Now is the time for all." ' to topic my_topic:

and the following also.

Connection to node 1007 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.

I suspect I am not being able to run Kafka properly.

I running Kafka and zookeeper using docker-compose.

Here is the content of my docker-compose.yml file.

version: '3'
services:
 zookeeper:
  image: wurstmeister/zookeeper
  container_name: zookeeper_anusheel
  restart: always
  logging:
   driver: json-file
   options:
     max-size: 1m
     max-file: '5'
  ports:
  - "2181:2181"

 kafka:
  image: wurstmeister/kafka
  container_name: kafka_anusheel
  restart: always
  ports:
   - "9092:9092"
  depends_on:
   - zookeeper
  links:
   - zookeeper:zookeeper
  logging:
   driver: json-file
   options:
     max-size: 1m
     max-file: '5'
  environment :
    KAFKA_ADVERTISED_HOST_NAME: localhost
    KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
    KAFKA_CREATE_TOPICS: "my_topic:2:1"

And when I am running the docker-compose up I am getting the following logs from Kafka. I suspect the Kafka is not configured properly.

docker-compose logs when running the Kafka

Source: Docker Questions