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 - 2. Changing the Server Port in
application.properties - 3. Setting the Port Using Environment Variables
- 4. Setting a Random Port
- 5. Download Source Code
- 6. References
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:
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/:
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.