title: Spring Boot: How do get tomcat port at runtime?
body: <p>I'm experimenting with Netflix OSS for implementing a microservice architecture. I wanted to log <code>server.port</code> from <em>bootstrap.yml</em> file at <strong>runtime</strong> to see which instance is serving the request.</p>
  
  <p>I'm using Java8.  </p>
  
  <p>Important libraries versions are:<br>
  * spring-boot-starter-web-1.5.8<br>
  * spring-boot-starter-tomcat-1.5.8<br>
  * tomcat-embed-core-8.5.23  </p>
  
  <p>After browsing on stackoverflow, I found <a href="https://stackoverflow.com/questions/36567207/get-spring-boot-management-port-at-runtime-when-management-port-0">this</a> and <a href="https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot">this</a> but these solution did not work.</p>
  
  <p>My bootstrap.yml looks like this:   </p>
  
  <pre><code>spring:
    application:
      name: some-service
  
  server:
    port: ${port:8088}
  </code></pre>
  
  <p>I have tried following code:</p>
  
  <pre><code>@SpringBootApplication
  @EnableEurekaClient
  @SuppressWarnings("javadoc")
  public class SomeService {
  
      private static Logger logger  = LoggerFactory.getLogger(SomeService .class);
  
      @LocalServerPort
      private static int randomServerPort;
  
      @LocalManagementPort
      private static int randomManagementPort;
  
      @Autowired
      private static Environment environment;
  
      @Value("${server.port}")
      // @Value("${local.server.port}")
      private static int port;
  
      public static void main(String[] args) {
          SpringApplication.run(SomeService .class, args);
  
          logger.info("randomServerPort : {}", randomServerPort);
          logger.info("randomManagementPort : {}", randomManagementPort);
          logger.info("server.port : {}", port);
          logger.info("environment.getProperty(\"server.port\") : {}", environment.getProperty("server.port"));
  
  }
  </code></pre>
  
  <p>Corresponding output is:</p>
  
  <pre><code>randomServerPort : 0
  randomManagementPort : 0
  server.port : 0
  java.lang.NullPointerException against environment.getProperty("server.port")
  </code></pre>
  
  <p>First three log statements log <code>0</code>, while last one throws a `NullPointerException*.</p>
  
  <p>At runtime, the port gets printed in logs on console as:</p>
  
  <pre><code>s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8088 (http)
  </code></pre>
  
  <p>I want to access this port number in <code>main</code> method of <code>SomeService</code> class. How can I do this?</p>