So you've got your lovely Spring Boot application ready to go. You launch it and find that it listens on the same port (8080) as something else you're working with.

What's a developer to do?

Easy. Tell Spring Boot to listen on a different port.

And in this guide I'll show you how to make that happen.

With Properties Configuration

The easiest way, and the way you should probably go with, is to update your file to point to the new port.

It's this simple:


Now, instead of listening on port 8080, your Spring Boot application will listen on port 36020.

And when you start it up, you'll see words to that effect.

INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 36020 (http) with context path ''

That's how you know that Spring got the message from your switch.

By the way, you could do the same thing with application.yml, if that's how you roll:

  port : 36020

Either one of those files is located in the src/main/resources directory of your source tree.

The Programmatic Way

If you like doing things the hard way, you could also configure the port programmatically.

Just drop a class like this one into one of the packages the Spring scans:

public class ServerConfig implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    public void customize(ConfigurableWebServerFactory factory) {

That will, once again, force the application to listen on port 36020.

But I don't recommend that. A port configuration really belongs in the properties file.

At the Command Line

Remember, lots of stuff you set in can also be set at the command line.

So if you need to make a run-time decision about which port to use, you can do something like this:

java -jar yourapp.jar --server.port=36020

That's the kind of thing you'd put in your Dockerfile at ENTRYPOINT. Assuming that's how you're packaging and deploying your application.

Which Order?

What happens if you configure a different port in multiple locations?

One of them is going to win. That's what will happen.

The properties file, believe it or not, is at the bottom of the food chain. So whatever you put in there gets lowest priority.

The next lowest priority is the command line argument.

The highest priority is the embedded server configuration.

Wrapping It Up

There you have it. An easy way to configure a custom port with Spring Boot.

Just make sure you don't pick a custom port that's already in use!

Have fun!

Photo by Albin Berlin from Pexels