Skip to content

서버 엔진 ​

Ktor 서버 애플리케이션을 실행하려면 먼저 서버를 생성하고 구성해야 합니다. 서버 구성에는 다음과 같은 다양한 설정이 포함됩니다.

  • 네트워크 요청을 처리하기 위한 엔진
  • 서버에 접근하는 데 사용되는 호스트 및 포트 값
  • SSL 설정

지원되는 플랫폼 ​

아래 표는 각 엔진이 지원하는 플랫폼을 나열합니다.

엔진플랫폼HTTP/2
NettyJVM✅
JettyJVM✅
TomcatJVM✅
CIO (Coroutine-based I/O)JVM, Native, GraalVM, JavaScript, WasmJs✖️
ServletApplicationEngineJVM✅

의존성 추가 ​

원하는 엔진을 사용하기 전에 빌드 스크립트에 해당하는 의존성을 추가해야 합니다.

  • ktor-server-netty
  • ktor-server-jetty-jakarta
  • ktor-server-tomcat-jakarta
  • ktor-server-cio

다음은 Netty 의존성을 추가하는 예시입니다.

kotlin
implementation(ktorLibs.server.netty)
위 코드 스니펫은 Ktor 의존성을 지정하기 위해 Ktor 버전 카탈로그(version catalog)를 사용합니다.
groovy
implementation ktorLibs.server.netty
위 코드 스니펫은 Ktor 의존성을 지정하기 위해 Ktor 버전 카탈로그(version catalog)를 사용합니다.
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-netty-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

서버 생성 방식 선택 ​

Ktor 서버 애플리케이션은 두 가지 방식으로 생성 및 실행할 수 있습니다.

  • 코드에서 서버 매개변수를 빠르게 전달하기 위해 embeddedServer 사용
  • 외부 application.conf 또는 application.yaml 파일에서 설정을 로드하기 위해 EngineMain 사용

embeddedServer ​

embeddedServer() 함수는 특정 유형의 엔진을 생성하는 데 사용되는 엔진 팩토리를 인자로 받습니다. 아래 예시에서는 Netty 엔진으로 서버를 실행하고 8080 포트에서 수신 대기하도록 Netty 팩토리를 전달합니다.

kotlin
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main(args: Array<String>) {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

EngineMain ​

EngineMain은 서버를 실행하기 위한 엔진을 나타냅니다. 다음과 같은 엔진을 사용할 수 있습니다.

  • io.ktor.server.netty.EngineMain
  • io.ktor.server.jetty.jakarta.EngineMain
  • io.ktor.server.tomcat.jakarta.EngineMain
  • io.ktor.server.cio.EngineMain

서버 생성 및 시작 ​

EngineMain.main() 함수는 선택한 엔진으로 서버를 시작하고 외부 설정 파일에 지정된 애플리케이션 모듈을 로드하는 데 사용됩니다. 아래 예시에서는 애플리케이션의 main 함수가 서버를 시작합니다.

kotlin
package com.example

import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

fun Application.module() {
    routing {
        get("/") {
            call.respondText("Hello, world!")
        }
    }
}
shell
ktor {
    deployment {
        port = 8080
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}
yaml
ktor:
    deployment:
        port: 8080
    application:
        modules:
            - com.example.ApplicationKt.module

빌드 시스템 작업을 사용하여 서버를 시작해야 하는 경우, 필요한 EngineMain을 메인 클래스로 구성해야 합니다.

kotlin
application {
    mainClass.set("io.ktor.server.netty.EngineMain")
}
groovy
mainClassName = "io.ktor.server.netty.EngineMain"
xml
<properties>
    <main.class>io.ktor.server.netty.EngineMain</main.class>
</properties>

서버를 시작하지 않고 인스턴스만 생성하기 ​

EngineMain.main()을 직접 호출하여 서버를 즉시 시작하는 것 외에도, 서버를 시작하지 않고 EmbeddedServer 인스턴스를 반환하는 EngineMain.createServer()를 호출할 수 있습니다.

이 접근 방식을 사용하면 .start(), .stop()을 호출하거나 서버가 요청을 수락하기 전에 수행할 작업을 직접 제어할 수 있습니다.

Kotlin
// Netty를 사용하는 예시
val server = io.ktor.server.netty.EngineMain.createServer(args)
// 추가 초기화, 로깅, 계측(instrumentation) 등 수행
server.start(wait = true)

엔진 구성 ​

이 섹션에서는 엔진별 다양한 옵션을 지정하는 방법을 살펴봅니다.

코드에서 구성 ​

embeddedServer 함수를 사용하면 configure 매개변수를 통해 엔진별 옵션을 전달할 수 있습니다. 이 매개변수에는 모든 엔진에 공통이며 ApplicationEngine.Configuration 클래스에서 노출하는 옵션이 포함됩니다.

아래 예시는 Netty 엔진을 사용하여 서버를 구성하는 방법을 보여줍니다. configure 블록 내에서 connector를 정의하여 호스트와 포트를 지정하고, 다양한 서버 매개변수를 커스터마이즈합니다.

kotlin
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main(args: Array<String>) {
    embeddedServer(Netty, configure = {
        connectors.add(EngineConnectorBuilder().apply {
            host = "127.0.0.1"
            port = 8080
        })
        connectionGroupSize = 2
        workerGroupSize = 5
        callGroupSize = 10
        shutdownGracePeriod = 2000
        shutdownTimeout = 3000
    }) {
        routing {
            get("/") {
                call.respondText("Hello, world!")
            }
        }
    }.start(wait = true)
}

connectors.add() 메서드는 지정된 호스트(127.0.0.1) 및 포트(8080)를 가진 커넥터를 정의합니다.

이러한 옵션 외에도 다른 엔진별 속성을 구성할 수 있습니다.

Netty

Netty 전용 옵션은 NettyApplicationEngine.Configuration 클래스에서 노출됩니다.

kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main() {
    embeddedServer(Netty, configure = {
        requestQueueLimit = 16
        shareWorkGroup = false
        configureBootstrap = {
            // ...
        }
        responseWriteTimeoutSeconds = 10
    }) {
        // ...
    }.start(true)
}

Jetty

Jetty 전용 옵션은 JettyApplicationEngineBase.Configuration 클래스에서 노출됩니다.

Jetty 서버는 Server 인스턴스에 대한 접근을 제공하는 configureServer 블록 내부에서 구성할 수 있습니다.

연결이 닫히기 전까지 유휴 상태로 유지될 수 있는 시간을 지정하려면 idleTimeout 속성을 사용하세요.

kotlin
import io.ktor.server.engine.*
import io.ktor.server.jetty.jakarta.*

fun main() {
    embeddedServer(Jetty, configure = {
        configureServer = { // this: Server -&gt;
            // ...
        }
        idleTimeout = 30.seconds
    }) {
        // ...
    }.start(true)
}

CIO

CIO 전용 옵션은 CIOApplicationEngine.Configuration 클래스에서 노출됩니다.

kotlin
import io.ktor.server.engine.*
import io.ktor.server.cio.*

fun main() {
    embeddedServer(CIO, configure = {
        connectionIdleTimeoutSeconds = 45
    }) {
        // ...
    }.start(true)
}

Tomcat

Tomcat을 엔진으로 사용하는 경우, Tomcat 인스턴스에 대한 접근을 제공하는 configureTomcat 속성을 사용하여 구성할 수 있습니다.

kotlin
import io.ktor.server.engine.*
import io.ktor.server.tomcat.jakarta.*

fun main() {
    embeddedServer(Tomcat, configure = {
        configureTomcat = { // this: Tomcat -&gt;
            // ...
        }
    }) {
        // ...
    }.start(true)
}

설정 파일에서 구성 ​

EngineMain을 사용하는 경우 ktor.deployment 그룹 내에서 모든 엔진에 공통적인 옵션을 지정할 수 있습니다.

shell
ktor {
    deployment {
        connectionGroupSize = 2
        workerGroupSize = 5
        callGroupSize = 10
        shutdownGracePeriod = 2000
        shutdownTimeout = 3000
    }
}
yaml
ktor:
    deployment:
        connectionGroupSize: 2
        workerGroupSize: 5
        callGroupSize: 10
        shutdownGracePeriod: 2000
        shutdownTimeout: 3000

Netty

설정 파일의 ktor.deployment 그룹 내에서 Netty 전용 옵션을 구성할 수도 있습니다.

shell
ktor {
    deployment {
        maxInitialLineLength = 2048
        maxHeaderSize = 1024
        maxChunkSize = 42
    }
}
yaml
ktor:
    deployment:
        maxInitialLineLength: 2048
        maxHeaderSize: 1024
        maxChunkSize: 42