Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Building and running a jar

The mn:run goal is only for development. An application goes to a server as one file, an executable jar (also called a fat jar or uber jar). It contains both your classes and all the libraries: Micronaut, Netty, the H2 driver. To run such a file, the server only needs Java 25.

Building

From the project folder:

./mvnw package

Maven compiles the code, runs all the tests and packages the result. At the end:

[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- shade:3.6.2:shade (default-shade) @ blog ---
[INFO] Replacing original artifact with shaded artifact.
[INFO] BUILD SUCCESS

Two files appear in the target folder:

FileSizeWhat it is
blog-0.1.jarabout 23 MBAn executable jar with all libraries
original-blog-0.1.jarabout 250 KBOnly your classes

The libraries are merged by maven-shade-plugin, configured by the micronaut-parent parent POM. The file name and version come from <artifactId> and <version> in pom.xml. You can skip tests during the build with -DskipTests, but it is better not to.

Running

java -jar target/blog-0.1.jar
INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO  io.micronaut.runtime.Micronaut - Startup completed in 1439ms. Server Running: http://localhost:8080

The application is up and answering: curl http://localhost:8080/health returns {"status":"UP"}. Stop it with Ctrl+C.

Server settings

The built jar is the same for every environment; only the settings differ. They are passed as environment variables at startup:

MICRONAUT_ENVIRONMENTS=prod \
JWT_SECRET=pleaseChangeThisSecretForANewOne \
MICRONAUT_SERVER_PORT=8080 \
java -jar target/blog-0.1.jar

The log shows Established active environments: [prod], and Micronaut reads application-prod.properties if it exists. The MICRONAUT_SERVER_PORT variable is the micronaut.server.port key written by the rules from the settings lesson. The real database address is set the same way: DATASOURCES_DEFAULT_URL, DATASOURCES_DEFAULT_USERNAME, DATASOURCES_DEFAULT_PASSWORD.

What to set on the serverVariable
EnvironmentMICRONAUT_ENVIRONMENTS=prod
PortMICRONAUT_SERVER_PORT
JWT secretJWT_SECRET
DatabaseDATASOURCES_DEFAULT_URL and others

Containers

Micronaut can build a Docker image right away: ./mvnw package -Dpackaging=docker. Docker must be running on your computer for this. The image contains Java and your jar. Start it with docker run -p 8080:8080 and the image name Maven prints at the end of the build.

Common mistake

If you run the file without libraries by mistake, Java cannot find the main class:

java -jar target/original-blog-0.1.jar
no main manifest attribute, in target\original-blog-0.1.jar

Run blog-0.1.jar, the file without the original prefix.

Thanks for reading!

Donate to the site — we work hard for you.