title: KafkaContainer - how to read kafka container port as property in Spring Boot after start() / how to configure Kafka port before starting
body: <p>I am doing integration testing with <code>KafkaContainer</code>; after starting the container, the port is chosen randomly.</p>
  <p>I can get the port by <code>container.getBootStrapServer()</code>, but what I need is to put the dynamic host+port in the properties (<code>application-itest.yml</code>, under <code>spring.kafka.bootstrap-servers</code>, because that is where Spring Kafka picks the value to configure my bean of <code>KafkaTemplate</code>).</p>
  <p>Or, if I can set the port to be a static value while starting <code>KafkaContainer</code>, like <code>9999</code>, and set it in the yaml file, it also will work. I don't know how to do neither.(Do I need to inject another bean of <code>KafkaTemplate</code> after getting the value?)</p>
  <p>How do I start KafkaContainer:</p>
  <pre><code>    public static final KafkaContainer kafka = new KafkaContainer(
              DockerImageName.parse(&quot;confluentinc/cp-kafka:5.4.3&quot;)
      );
      private AdminClient adminClient;
  
      ...
  
      @BeforeEach
      void setup() {
          if (adminClient == null) {
              kafka.start();
              // here value is dynamic and is not accessible in Environment; not as `@AutoConfigureWiremock`, I have `wiremock.server` value set after)
              String bootStrapServer = kafka.getBootstrapServers();
              log.info(&quot;Kafka container created at: {}&quot;, bootStrapServer);
              adminClient = AdminClient.create(Map.of(
                      AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServer
              ));
              // create my topic
              log.info(&quot;Current topic: {}&quot;, topic);
              adminClient.createTopics(Set.of(
                      new NewTopic(topic, 4, (short) 1)
              ));
          }
      }
  
  </code></pre>