Building and distributing programs

suggest change

A Kotlin program on the JVM compiles to .class files. To give it to someone else you have to package those classes, the Kotlin standard library and all other dependencies into something they can run.

There are several ways to ship a Kotlin program, depending on what you can expect the user to have installed:

Format What the user needs Tool
Single JAR from kotlinc a JVM kotlinc -include-runtime
Start scripts + lib/ folder a JVM Gradle application plugin
Fat (uber) JAR a JVM Shadow plugin
App image or installer with bundled JVM nothing jlink + jpackage
Native executable from JVM code nothing GraalVM native-image
Native executable from Kotlin/Native nothing Kotlin Multiplatform plugin
Container image Docker or Kubernetes Dockerfile

This article walks through each one using the same small command-line program.

The quickest way: kotlinc

For a single file with no dependencies you don't need a build tool. Write hello.kt:

fun main(args: Array<String>) {
    val name = args.firstOrNull() ?: "World"
    println("Hello, $name!")
}

Compile it into a JAR that contains the Kotlin runtime:

$ kotlinc hello.kt -include-runtime -d hello.jar
$ java -jar hello.jar Kotlin
Hello, Kotlin!

-include-runtime copies the Kotlin standard library into the JAR and kotlinc writes a Main-Class entry to the manifest, so java -jar knows what to run. Without -include-runtime the JAR is smaller, but it fails with NoClassDefFoundError: kotlin/jvm/internal/Intrinsics unless you put kotlin-stdlib.jar on the classpath yourself.

A top-level main in hello.kt is compiled into a class named HelloKt. You can rename that class with an annotation at the top of the file:

@file:JvmName("Hello")

fun main() = println("Hello!")

See Compile and Run Kotlin Code in Command Line for more about kotlinc and kotlin.

As soon as you need a library, use a build tool. The rest of this article uses Gradle with the Kotlin DSL.

A Gradle project

The example program is a small CLI built with Clikt. The project layout:

greet/
├── settings.gradle.kts
├── build.gradle.kts
├── gradlew, gradlew.bat, gradle/wrapper/...
└── src/main/kotlin/app/Main.kt

settings.gradle.kts names the project. The project name becomes the name of the JAR, the start scripts and the distribution:

plugins {
    // downloads a JDK if the one requested by jvmToolchain() is not installed
    id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
}

rootProject.name = "greet"

build.gradle.kts:

plugins {
    kotlin("jvm") version "2.4.21"
    application
}

group = "com.example"
version = "1.0.0"

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.github.ajalt.clikt:clikt:5.1.0")
}

kotlin {
    jvmToolchain(25)
}

application {
    mainClass = "app.MainKt"
    // Clikt's terminal library calls native code; avoids a JVM warning on Java 24+
    applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED")
}

tasks.withType<Jar>().configureEach {
    manifest {
        attributes(
            "Implementation-Version" to project.version,
            "Enable-Native-Access" to "ALL-UNNAMED", // same, for java -jar
        )
    }
}

src/main/kotlin/app/Main.kt:

package app

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.main
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.versionOption
import com.github.ajalt.clikt.parameters.types.int

// Implementation-Version from the JAR manifest; null when running from class files
val appVersion: String = Greet::class.java.`package`?.implementationVersion ?: "dev"

class Greet : CliktCommand(name = "greet") {
    private val name by argument()
    private val times by option("-n", "--times").int().default(1)

    init {
        versionOption(appVersion)
    }

    override fun run() {
        repeat(times) { echo("Hello, $name!") }
    }
}

fun main(args: Array<String>) = Greet().main(args)

The main function lives in Main.kt in package app, so the JVM class is app.MainKt. That is the value for mainClass. Getting this wrong is the most common reason for Could not find or load main class.

Always commit the Gradle wrapper (gradlew, gradlew.bat, gradle/wrapper/). It pins the Gradle version so every developer and CI machine builds the same way. Create or update it with:

$ gradle wrapper --gradle-version 9.8.1

During development, run the program through Gradle. Program arguments go in --args:

$ ./gradlew run --args="Kotlin -n 2"
Hello, Kotlin!
Hello, Kotlin!

For more about the Kotlin Gradle plugin see Gradle configuration; for parsing arguments see Command-line arguments.

Distribution with start scripts

The application plugin can produce a ready-to-run folder with start scripts for Unix and Windows:

$ ./gradlew installDist
$ ls build/install/greet/bin build/install/greet/lib
build/install/greet/bin:
greet  greet.bat

build/install/greet/lib:
clikt-jvm-5.1.0.jar  greet-1.0.0.jar  kotlin-stdlib-2.4.21.jar  ...
$ build/install/greet/bin/greet World
Hello, World!
$ build/install/greet/bin/greet --version
greet version 1.0.0

Your code stays in its own small greet-1.0.0.jar and every dependency keeps its own JAR in lib/. The scripts build the classpath, find Java through JAVA_HOME or the PATH, and pass arguments through.

To get an archive you can upload to a release page:

$ ./gradlew distZip distTar
$ ls build/distributions
greet-1.0.0.tar  greet-1.0.0.zip

JVM options can be baked into the scripts. Users can still add their own through the JAVA_OPTS or GREET_OPTS environment variables:

application {
    mainClass = "app.MainKt"
    applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED", "-Xmx256m", "-XX:+UseSerialGC")
}

Files in src/dist/ are copied into the root of the distribution. That is the place for a README, a LICENSE or a default configuration file.

This format is simple and debuggable: you can see exactly which library versions ship. The drawback is that it is a folder, not a single file, and the user still needs a JVM.

Fat JAR with Shadow

A fat JAR (also called an uber JAR) puts your classes and all dependencies into one file that runs with java -jar. Use the Shadow plugin:

plugins {
    kotlin("jvm") version "2.4.21"
    application
    id("com.gradleup.shadow") version "9.6.1"
}

// ... same as before ...

tasks.shadowJar {
    // merge META-INF/services files from all JARs instead of keeping only one
    mergeServiceFiles()
}
$ ./gradlew shadowJar
$ ls build/libs
greet-1.0.0-all.jar  greet-1.0.0.jar
$ java -jar build/libs/greet-1.0.0-all.jar World -n 2
Hello, World!
Hello, World!

When the application plugin is applied, Shadow takes Main-Class from application.mainClass and inherits the manifest attributes of the jar task, so Implementation-Version is there too.

Why a plugin instead of a hand-written Jar task that unzips all dependencies? Because JARs contain files with the same path:

Shadow handles these cases. It can also relocate (rename) packages of a dependency, which avoids conflicts when your JAR will be loaded next to another version of the same library:

tasks.shadowJar {
    relocate("com.google.gson", "com.example.greet.shaded.gson")
}

Shadow also has minimize(), which removes classes that are not referenced. Use it with care: classes loaded by reflection or ServiceLoader look unused and get removed.

A fat JAR still needs a JVM on the user's machine. Since JDK 14, the JDK ships jpackage, which bundles your application with a Java runtime into an app folder or a native installer (.msi, .exe, .dmg, .pkg, .deb, .rpm).

A full JDK is large, so first build a runtime that contains only the modules you use. jdeps finds them:

$ jdeps --print-module-deps --ignore-missing-deps --multi-release 25 \
    build/libs/greet-1.0.0-all.jar

It prints a comma-separated module list such as java.base,java.logging. Pass that list to jlink:

$ jlink --add-modules java.base,java.logging \
    --strip-debug --no-header-files --no-man-pages --compress zip-6 \
    --output build/runtime
$ build/runtime/bin/java -jar build/libs/greet-1.0.0-all.jar World
Hello, World!

The trimmed runtime is usually a few tens of MB instead of a few hundred. If the program later fails with NoClassDefFoundError for a java.* or javax.* class, a module that is only used through reflection is missing. Add it to --add-modules.

Then let jpackage create an application image. Put only the fat JAR in the input folder, because jpackage copies everything it finds there:

$ mkdir -p build/jpackage-input
$ cp build/libs/greet-1.0.0-all.jar build/jpackage-input/
$ jpackage --type app-image \
    --name greet --app-version 1.0.0 \
    --input build/jpackage-input --main-jar greet-1.0.0-all.jar \
    --runtime-image build/runtime \
    --dest build/dist

The result is a folder with a native launcher and the bundled runtime: build/dist/greet/bin/greet on Linux, build/dist/greet/greet.exe on Windows and build/dist/greet.app on macOS. Zip the folder and the user doesn't need to install Java.

A few things to know:

You can run these commands from Gradle with Exec tasks, or use a plugin such as org.beryx.runtime that wraps jlink and jpackage.

Native executable with GraalVM

GraalVM native-image compiles JVM bytecode ahead of time into a standalone executable. It starts in milliseconds and uses much less memory than a JVM, which matters for CLI tools and short-lived serverless functions. Peak throughput of long-running programs is usually lower than with the JIT, and builds are slow (tens of seconds to minutes).

Install a GraalVM JDK (for example with SDKMAN: sdk install java 25-graal), make it JAVA_HOME, and add the official Gradle plugin:

plugins {
    kotlin("jvm") version "2.4.21"
    application
    id("org.graalvm.buildtools.native") version "1.1.14"
}

graalvmNative {
    binaries {
        named("main") {
            imageName = "greet"
            mainClass = "app.MainKt"
        }
    }
}
$ ./gradlew nativeCompile
$ build/native/nativeCompile/greet World
Hello, World!

The executable doesn't need Java, but it is built for one OS and CPU architecture. As with jpackage, build each platform on its own machine.

native-image works under a closed-world assumption: everything reachable must be known at build time. Reflection, dynamic proxies, resources and ServiceLoader lookups that it can't see statically need configuration files in META-INF/native-image/. Many popular libraries ship this configuration, and the plugin downloads more from the GraalVM reachability metadata repository. For the rest, run the program on the JVM with the tracing agent, exercise the code paths, and copy the generated configuration into your sources:

$ ./gradlew -Pagent run --args="World"
$ ./gradlew metadataCopy --task run --dir src/main/resources/META-INF/native-image

Test the native binary, not only the JVM build. Missing configuration shows up only at runtime, as ClassNotFoundException or a missing resource.

Native executable with Kotlin/Native

Kotlin/Native compiles Kotlin source code (not JVM bytecode) to native code with LLVM. There's no JVM involved at any point, so you can't use Java libraries such as java.io.File or JDBC drivers. You can use the Kotlin standard library and multiplatform libraries that support native targets. Clikt is one of them.

The project uses the multiplatform plugin and code goes into src/commonMain/kotlin (or src/nativeMain/kotlin):

import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget

plugins {
    kotlin("multiplatform") version "2.4.21"
}

repositories {
    mavenCentral()
}

kotlin {
    linuxX64()
    mingwX64()
    macosArm64()

    targets.withType<KotlinNativeTarget>().configureEach {
        binaries {
            executable {
                entryPoint = "app.main"
                baseName = "greet"
            }
        }
    }

    sourceSets {
        commonMain.dependencies {
            implementation("com.github.ajalt.clikt:clikt:5.1.0")
        }
    }
}

Our Main.kt compiles unchanged except for appVersion, which uses JVM reflection. Replace it with a constant or a generated source file.

$ ./gradlew linkReleaseExecutableLinuxX64
$ build/bin/linuxX64/releaseExecutable/greet.kexe World
Hello, World!

On Windows the task is linkReleaseExecutableMingwX64 and the output is greet.exe. Linux and Windows targets can be cross-compiled from any host, but Apple targets can only be built on macOS.

Choose Kotlin/Native when you want a small native binary and your code only needs multiplatform libraries. Choose GraalVM when you have an existing JVM program or need Java libraries.

Container images

For servers, the usual unit of distribution is a container image. The installDist output fits well into a multi-stage Dockerfile: the first stage builds with a JDK, the second contains only a JRE and your program.

FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN ./gradlew --no-daemon installDist

FROM eclipse-temurin:25-jre
COPY --from=build /src/build/install/greet /opt/greet
ENTRYPOINT ["/opt/greet/bin/greet"]
$ docker build -t greet:1.0.0 .
$ docker run --rm greet:1.0.0 Docker -n 2
Hello, Docker!
Hello, Docker!

Keeping dependencies in separate JARs (instead of a fat JAR) has a benefit here too. If you copy lib/ in its own layer, before your code, a code change rebuilds only the small layer with your JAR. Add a .dockerignore that excludes build/ and .gradle/ so local build output isn't sent to the Docker daemon.

Modern JVMs read container memory and CPU limits. Use -XX:MaxRAMPercentage=75 instead of a fixed -Xmx so the heap follows the container limit.

Versioning and reproducible builds

Users and bug reports need to know which build is running. The example above writes project.version to the manifest and reads it with Package.implementationVersion. Another common approach is a generated resource:

tasks.processResources {
    val version = project.version.toString()
    inputs.property("version", version)
    filesMatching("version.properties") {
        expand("version" to version)
    }
}

with src/main/resources/version.properties containing version=${version}, read at runtime through ClassLoader.getResourceAsStream. See Configuration files for reading properties files.

To make JARs byte-for-byte reproducible (the same input produces the same file, which makes builds verifiable and caches more effective), drop timestamps and fix the file order:

tasks.withType<AbstractArchiveTask>().configureEach {
    isPreserveFileTimestamps = false
    isReproducibleFileOrder = true
}

Building releases in CI

Native installers and executables must be built on each target OS, so releases are usually built by CI. A GitHub Actions matrix that builds a GraalVM executable on three platforms:

name: release
on:
  push:
    tags: ["v*"]

jobs:
  build:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v5
      - uses: graalvm/setup-graalvm@v1
        with:
          java-version: "25"
          distribution: graalvm
      - uses: gradle/actions/setup-gradle@v5
      - run: ./gradlew nativeCompile
      - uses: actions/upload-artifact@v4
        with:
          name: greet-${{ matrix.os }}
          path: build/native/nativeCompile/greet*

setup-gradle caches dependencies and the Gradle distribution between runs. Running ./gradlew works on the Windows runner too, because steps there use PowerShell, which runs gradlew.bat.

Choosing a format

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents