Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Friday, August 11, 2023

6 Ways to Change Default Port in Spring Boot? Example Tutorial

Hello Java programmers, when developing a Spring Boot application, we often need to configure the port on which our Spring Boot application runs as the default port most likely already occupied. The default port for a Spring Boot application is 8080, but in certain scenarios, you may want to change it to a different port number as its too common and you may find that some other application is using it already. In this article, we'll explore different methods to configure the port for a Spring Boot application, allowing you to customize the port according to your requirements. You can use any of them to configure the port you want for your Spring Boot application.


How To Configure port for a Spring Boot Application? Examples

Here are multiple ways to configure port for embedded server in Spring Boot application

Method 1: Application Properties

One way to configure the port for a Spring Boot application is by modifying the application.properties file. This file contains various configuration properties for your application, including the server port. To change the port, open the application.properties file and add the following line:

server.port=your_desired_port_number

Replace your_desired_port_number with the port number you want to use. Save the file and restart your Spring Boot application. Your application will now run on the specified port.

Method 2: YAML Configuration

If you're using YAML configuration instead of the application.properties file, you can configure the port in your application.yml file. Add the following lines to specify the desired port:

server:
  port: your_desired_port_number

Replace your_desired_port_number with the port number you want to use. Save the file and restart your Spring Boot application to apply the changes.


Method 3: Command Line Argument

Another approach to configuring the port is by providing a command line argument when running your Spring Boot application. Instead of hardcoding the port in your configuration files, you can pass it as a command line argument during application startup.

Open your terminal or command prompt and navigate to the directory containing your Spring Boot application's JAR file. 

Then run the following command:

$ java -jar -Dserver.port=your_desired_port_number your_application.jar

Replace your_desired_port_number with the port number you want to use and your_application.jar with the actual name of your Spring Boot application's JAR file. This command sets the server.port system property to the specified port number.

Method 4: Environment Variable

If you prefer to configure the port using environment variables, you can do so by setting the SERVER_PORT variable. The Spring Boot application will automatically pick up this variable and use it as the port. 

Set the SERVER_PORT environment variable to your desired port number before starting your application. The process for setting environment variables may vary depending on your operating system or deployment environment.




Method 5: Programmatically in Code

In certain cases, you may want to configure the port programmatically in your Java code. To achieve this, create a configuration class and annotate it with @Configuration. Then, define a bean of type EmbeddedServletContainerCustomizer to customize the embedded servlet container settings. 

Here's an example:
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;

@Configuration
public class PortConfiguration {

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (ConfigurableEmbeddedServletContainer container) -> {
            container.setPort(your_desired_port_number);
        };
    }
}

Again you need to replace your_desired_port_number with the port number you want to use. By implementing this customizer, you can programmatically set the port for your Spring Boot application.

Method 6: Configuring Port Range

In some cases, you may need to configure a range of ports instead of a specific port. This can be useful when running multiple instances of your Spring Boot application or when deploying in a clustered environment. To configure a port range, you can modify the application.properties file or use any of the previously mentioned methods.

To configure a port range in application.properties, use the following syntax:

server.port=your_starting_port_number-your_ending_port_number

Replace your_starting_port_number and your_ending_port_number with the desired range of port numbers. For example, server.port=8080-8090 configures the application to run on ports ranging from 8080 to 8090.

Alternatively, you can apply the same configurations using YAML, command line arguments, environment variables, or programmatically in code, as discussed in the previous methods.



Method 7: Random Port Allocation

Spring Boot provides an option to allocate a random available port for your application. This can be useful in scenarios where you don't want to hardcode a specific port and instead let the system assign an available port dynamically. 

To enable random port allocation, simply omit the server.port configuration in your application.properties or application.yml file.

When the application starts, Spring Boot automatically assigns an available port. You can retrieve the dynamically allocated port programmatically using the getLocalPort() method from the EmbeddedWebApplicationContext or WebServerApplicationContext classes. This allows you to log or display the assigned port during runtime.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class PortLogger {

    @Autowired
    private WebServerApplicationContext applicationContext;

    public void logPort() {
        int port = applicationContext.getWebServer().getPort();
        System.out.println("Application is running on port: " + port);
    }
}


In the example above, the PortLogger component logs the assigned port during runtime.

Method 8: Reverse Proxy Configuration

In certain deployment scenarios, you may have a reverse proxy server, such as Nginx or Apache, sitting in front of your Spring Boot application. In this case, you can configure the port indirectly through the reverse proxy server.

The reverse proxy server listens on a specific port and forwards requests to the backend Spring Boot application. To configure the port, modify the configuration file of your reverse proxy server and specify the desired port there. Typically, this involves updating the server configuration block or virtual host configuration.

For example, in an Nginx configuration file, you can set up a server block as follows:

server {
    listen 80;
    server_name your_domain.com;

    location / {
        proxy_pass http://localhost:your_desired_port_number;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
Replace your_desired_port_number with the port number where your Spring Boot application is running. Save the configuration file and restart the reverse proxy server. Requests received on the specified port will be forwarded to your Spring Boot application.

Conclusion

That's all about how to configure port for a spring Boot application. Configuring the port for a Spring Boot application gives you control over the network port on which your application listens. In this article, we explored different methods to configure the port, including using configuration files, command line arguments, environment variables, and programmatically in code. We also discussed configuring port ranges and enabling random port allocation.

By selecting the appropriate method based on your requirements, you can effectively customize the port configuration for your Spring Boot application. Whether you need a specific port, a range of ports, or dynamic allocation, Spring Boot provides the flexibility to adapt to your needs and ensure smooth application deployment and operation.

Other Spring MVC articles and Tutorials you may like

Thanks a lot for reading this article so far. If you like this Spring Boot Tutorial  then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments :

Post a Comment