Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Deployment and Coroutines

Packaging and Deploying Ktor with Docker

Package a Ktor server as a fat JAR or distribution, build a small multi-stage Docker image, tune the JVM for containers and understand layer caching, ports, users and health checks.

A Ktor server is just a JVM program. Deploying it means three steps: build one runnable artifact, put it into an image or a server with a Java runtime, and start it with the right settings. This lesson covers the artifact (fat JAR or distribution), a lean multi-stage Dockerfile, JVM options that behave in containers, and the details that make the difference between "works on my machine" and a deployment you can trust.

About the examples. The Gradle and Docker files below are real and read-only: the site cannot run Gradle or a Docker daemon. The runnable blocks are labelled stand-ins that model ideas such as layer caching or startup order in plain Kotlin.

Option 1: the fat JAR

A fat JAR (also called an uber JAR) contains your compiled classes and every dependency in one file, so java -jar app.jar is the whole deployment. The Ktor Gradle plugin adds a task for it:

Kotlin
// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.0"
    kotlin("plugin.serialization") version "2.4.0"
    id("io.ktor.plugin") version "3.4.0"
}

application {
    mainClass.set("io.ktor.server.netty.EngineMain")
}

ktor {
    fatJar {
        archiveFileName.set("tasks-api.jar")
    }
}

Build and run:

Terminal
./gradlew buildFatJar
java -jar build/libs/tasks-api.jar

EngineMain is Ktor's own entry point: it reads application.yaml, starts the engine (Netty here) and loads the modules listed under ktor.application.modules. You can also write your own fun main() that calls embeddedServer(...), which is handy for small apps and tests, but EngineMain is what lets the configuration file control the port and modules.

Option 2: the distribution

./gradlew installDist produces a folder with lib/ (one JAR per dependency) and a start script in bin/. Dependencies live in separate files, which matters for Docker layer caching (see below), because libraries change rarely and your own code changes constantly.

A multi-stage Dockerfile

Build in one image that has the JDK and Gradle, then copy only the result into a small runtime image:

DOCKERFILE
# ---- build stage ----
FROM gradle:8-jdk21 AS build
WORKDIR /home/gradle/src
COPY build.gradle.kts settings.gradle.kts gradle.properties* ./
RUN gradle dependencies --no-daemon > /dev/null 2>&1 || true
COPY src ./src
RUN gradle buildFatJar --no-daemon

# ---- runtime stage ----
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 10001 appuser
WORKDIR /app
COPY --from=build /home/gradle/src/build/libs/tasks-api.jar app.jar
USER appuser
ENV PORT=8080
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]

What this gives you:

  • Small final image. The runtime stage holds a JRE and one JAR, not Gradle, sources or caches.
  • Fast rebuilds. The dependencies step only reruns when the build files change. Editing a source file reuses the cached dependency layer.
  • Non-root user. If someone exploits the app, they do not own the container.
  • Config from the environment. ENV PORT=8080 pairs with the "$PORT:8080" placeholder from Configuration and Environments.

Build and run it:

Terminal
docker build -t tasks-api .
docker run --rm -p 8080:8080 -e JWT_SECRET=change-me-please-change-me-please tasks-api

For a deeper look at images and layers, the Docker tutorial has a full course.

How layer caching works (stand-in)

Each Dockerfile instruction creates a layer. Docker reuses a cached layer only if the instruction and everything it depends on is unchanged; once one layer changes, every layer after it is rebuilt. That is why the Dockerfile copies the build files first and the sources later. The stand-in below simulates that rule with a hash per layer.

Kotlin Stand-in: why instruction order matters for caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

With the good order, editing a source file rebuilds only the last two layers and the slow dependency download stays cached. With the bad order, any source edit invalidates the very first layer, so everything is rebuilt every time.

JVM options for containers

Modern JVMs read container limits, but you should still set the memory behavior on purpose:

  • -XX:MaxRAMPercentage=75 lets the heap use 75 percent of the container's memory limit, leaving room for metaspace, threads and native buffers. Do not set it near 100 percent; the container would be killed by the out-of-memory killer.
  • Set a container memory limit (docker run -m 512m) so the JVM can size itself.
  • Netty uses direct (off-heap) memory too, so a heap that fills the whole limit leaves it nothing.
  • Startup time matters for scale-to-zero platforms. Class data sharing and smaller dependency lists help; GraalVM native images are possible but need extra setup and reflection configuration.

Ports, hosts and proxies

  • Bind to 0.0.0.0 inside a container (ktor.deployment.host), not 127.0.0.1, or nothing outside the container can reach it.
  • Run on a high port (8080) and let the platform or a reverse proxy publish 80 and 443.
  • Behind a proxy or load balancer, install the forwarded-headers plugin so call.request.origin reports the client's real scheme and address; see Production Readiness.

Docker Compose for local environments

A Compose file starts your app together with a real database:

YAML
services:
  api:
    build: .
    ports: ["8080:8080"]
    environment:
      DATABASE_URL: jdbc:postgresql://db:5432/tasks
      DB_PASSWORD: devpassword
      JWT_SECRET: dev-secret-dev-secret-dev-secret-1
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devpassword
      POSTGRES_DB: tasks
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 10

depends_on with a health condition only orders container startup. Your app should still retry its database connection, because databases can restart at any time (see Connection Pooling and Migrations).

Startup order (stand-in)

A well-behaved service starts in a fixed order and fails clearly: read config, connect to the database, run migrations, then open the port. If any step fails, the process exits with a non-zero code so the platform restarts it.

Kotlin Stand-in: startup sequence with fail-fast and retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Running as root in the container.
  • Copying build/ or .gradle/ into the image because .dockerignore is missing.
  • Using latest tags for base images; pin a version so rebuilds are reproducible.
  • Baking secrets into the image with ENV lines or COPY .env.
  • Giving the JVM no memory limit and letting the container be killed with exit code 137.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a fat JAR contain?

    A fat JAR bundles dependencies so a single file is the whole app.
  2. 2. Why copy build.gradle.kts before the source files in a Dockerfile?

    A changed layer invalidates all later layers, so rarely changing inputs go first.
  3. 3. Why should a Ktor container bind to 0.0.0.0?

    Loopback is not reachable from outside the container's network namespace.
  4. 4. What is a reason to use a multi-stage build?

    Build tools stay in the first stage, giving a smaller and safer runtime image.

Summary

  • Build a fat JAR with buildFatJar (or a distribution with installDist) and start it with EngineMain.
  • Use a multi-stage Dockerfile, a JRE base image, a non-root user and build files copied before sources.
  • Set JVM memory with MaxRAMPercentage and a container limit; bind to 0.0.0.0.
  • Inject configuration and secrets through environment variables, never into the image.
  • Start in a fixed order, retry the database, and exit non-zero when startup fails.

Next: Production Readiness