Port Numbers

Those numbers such as 8080, 12345 that show up when doing networking things

When doing any kind of networking operation such as setting up or connecting to a server, the subject *Port Numbers arises.

Here’s what you should know about port numbers for working with web servers (or other network servers):

Error Port already in use

On any given host, only one process can use a port at a time. So if you already have a webserver running on 8080 in one window, and you try to start up a second one, you’ll get an error message such as Port already in use.

Solutions:

Ports and Spring Boot

When running a Spring Boot server, we typically define the port to be used in the file src/main/resources/application.properties with the following line of code:

server.port=${PORT:8080}

This line of code signifies that the server.port property should be defined as the value of the environment variable PORT if it exists; otherwise it should be the value 8080

Coding it without the environment variable fallback, as server.port=8080 will work on localhost, but will fail on Heroku. On Heroku, the cloud server will assign web servers (whether Spring Boot, Python Flask, Rails, or whatever) a port that they are expected to run on by specifying the PORT environment variable. If the server does not start up on the expected port within some reasonable timeout, say 15-20 seconds, then the process will be killed an error will be logged.

Therefore when running Spring Boot on Heroku, the server.port=${PORT:8080} form should always be used.