How to Change the Default Micronaut Server Port

By default, a Micronaut application runs on port 8080. In this guide, we will explore multiple ways to change the default Micronaut server port.

Table of Contents:

1. Changing the Server Port in `application.yml`

One of the easiest and most commonly used methods is updating the application.yml configuration file. Navigate to src/main/resources/application.yml and add the following configuration:

application.yml

micronaut:
  server:
    port: 9090

This configuration sets the server port to 9090. Restart the application, and it will now be accessible on http://localhost:9090.

2. Changing the Server Port in `application.properties`

If we prefer using a .properties file instead of YAML, we can update the application.properties file located in src/main/resources/:

application.properties

micronaut.server.port=9090

3. Setting the Port Using Environment Variables

Using environment variables is a flexible approach, especially for cloud deployments or CI/CD pipelines where hardcoded values are not ideal.

On Linux/macOS, run:


export MICRONAUT_SERVER_PORT=9090

On Windows (Command Prompt):


set MICRONAUT_SERVER_PORT=9090

On Windows (PowerShell):


$env:MICRONAUT_SERVER_PORT=9090

Real-World Use Case
When deploying a Micronaut application to AWS, Google Cloud, or Kubernetes, we might not know the required port in advance. Using an environment variable allows us to dynamically set the port based on the deployment environment.

4. Setting a Random Port

If we want the Micronaut server to run on a random port each time it starts, we can use the following configuration:


micronaut.server.port=-1

This is useful for integration tests where we need a new, available port for each test run.

5. Download Source Code

6. References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments