Skip to main content

How to Package and Deploy a ZIO HTTP Server

In this guide, we take a small ZIO HTTP server from sbt run to a Docker container that is ready to deploy. By the end, the server reads its port and shutdown timeout from environment variables, finishes the requests it is serving when the container is stopped, switches between development and production behavior with one variable, and ships as an image built by sbt-native-packager.

We start with the server code: one layer change makes it read its settings from the environment. Then we look at what happens when the platform stops the server, choose the mode, build the image, and finally run and stop a container to see every piece work together.

The Problem​

A server that works under sbt run is not yet ready to deploy. On a developer machine, the port is written in the code, the program runs inside sbt, and we stop it with Ctrl+C. A container platform such as Docker or Kubernetes works differently:

  • It runs a packaged application, not an sbt build, and expects to configure it with environment variables: the same image runs on port 8080 in one environment and on port 9000 in another.
  • It stops the application with a SIGTERM signal and, after a grace period, kills it with SIGKILL. A server that exits on SIGTERM without waiting drops the requests it is serving; a server that waits longer than the grace period is killed in the middle of them.
  • It runs the same image in development, staging, and production, so anything that should differ between them, such as how much detail an error response shows, has to come from the environment too.

Getting these wrong does not show up until a deployment: a request fails during every rollout, or the server ignores the port the platform gave it. In this guide, we solve each point with what ZIO HTTP already provides: the Server.configured layer, the server's graceful shutdown, and Mode.

Prerequisites​

Add ZIO HTTP to your build.sbt:

libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

The examples in this guide use these imports:

import zio._

import zio.http._

To build and run the image, you also need Docker installed. This guide assumes you know how to define routes and start a server.

The Server to Deploy​

The examples deploy a small server with two routes. GET /health answers at once, which is what a load balancer or a container health check calls. GET /report takes five seconds to answer, which gives us time to stop the server in the middle of a request later on:

object OrderRoutes {
val routes: Routes[Any, Response] =
Routes(
Method.GET / "health" -> handler(Response.text("OK")),
Method.GET / "report" -> handler(ZIO.sleep(5.seconds).as(Response.text("Report ready"))),
)
}

Reading Server Settings from the Environment​

Server.default always listens on port 8080. To let the environment decide, we provide Server.configured() instead. This layer loads a Server.Config with ZIO's configuration system, from the keys under zio.http.server, and builds the server from it:

object ConfiguredServer extends ZIOAppDefault {
val run =
Server.serve(OrderRoutes.routes).provide(Server.configured())
}

ZIO's default config provider reads environment variables first and JVM system properties second. An environment variable name is the key path in upper case, with _ between the parts and in place of -. These are the settings you are most likely to set when you deploy:

SettingEnvironment variableJVM system propertyDefault when not set
PortZIO_HTTP_SERVER_BINDING_PORTzio.http.server.binding-port8080
Host to bind toZIO_HTTP_SERVER_BINDING_HOSTzio.http.server.binding-host0.0.0.0 (all interfaces)
Time to wait for open requestsZIO_HTTP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUTzio.http.server.graceful-shutdown-timeout10 seconds
Close idle connections afterZIO_HTTP_SERVER_IDLE_TIMEOUTzio.http.server.idle-timeoutnever

Any key that is not set keeps the value of Server.Config.default. Durations accept forms such as 30s, 30 seconds, and PT30S. The Server Config reference lists every key.

To see what the layer reads, we can load the same configuration from a map of system-property keys:

val settings = ConfigProvider.fromMap(
Map(
"zio.http.server.binding-port" -> "9000",
"zio.http.server.graceful-shutdown-timeout" -> "30s",
),
)

val loaded: Server.Config =
Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe
.run(ZIO.withConfigProvider(settings)(ZIO.config(Server.Config.config.nested("zio", "http", "server"))))
.getOrThrowFiberFailure()
}

Then we look at a few fields of the result:

loaded.address.getPort
// res1: Int = 9000
loaded.gracefulShutdownTimeout
// res2: Duration = PT30S
loaded.keepAlive
// res3: Boolean = true

The port and the timeout come from the map, and keepAlive keeps its default. In a deployment, setting ZIO_HTTP_SERVER_BINDING_PORT=9000 and ZIO_HTTP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT=30s in the environment has the same effect.

One field differs from Server.default even when nothing is set: the configuration that Server.configured() reads enables request streaming unless its enabled key is false, while Server.Config.default disables it with a maximum content length of 100 KiB:

loaded.requestStreaming
// res4: Server.RequestStreaming = Enabled
Server.Config.default.requestStreaming
// res5: Server.RequestStreaming = Disabled(maximumContentLength = 102400)

To keep the behavior of Server.default, set ZIO_HTTP_SERVER_REQUEST_STREAMING_ENABLED=false, and ZIO_HTTP_SERVER_REQUEST_STREAMING_MAXIMUM_CONTENT_LENGTH to change the 102400-byte limit. Enabling Streaming of Request Bodies explains what each setting means for your handlers.

A value that cannot be read, such as a port of eighty, fails the Server.configured() layer with a RuntimeException whose message starts with Configuration error:, so the server stops at startup instead of running with a setting you did not intend.

tip

To read settings that are not part of Server.Config, such as a database URL, or to load them from a HOCON or YAML file, see How to Integrate with ZIO Config.

Shutting Down Gracefully​

A ZIOAppDefault installs a JVM shutdown hook, so when the process receives SIGTERM, ZIO interrupts the run effect and releases its layers. Releasing the server layer is where the graceful shutdown happens:

  1. The server closes its listening socket, so new connections are refused.
  2. It waits until the requests it is serving have finished, or until the graceful shutdown timeout has passed, whichever comes first.
  3. It shuts down Netty's event loops, which waits a quiet period of two seconds, and the JVM exits.

The timeout is 10 seconds by default. If some of your requests take longer, raise it with the environment variable from the previous section:

ZIO_HTTP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT=30s

If you build the configuration in code instead, set the same field with Server.Config#gracefulShutdownTimeout:

object CodeConfiguredServer extends ZIOAppDefault {
val run =
Server
.serve(OrderRoutes.routes)
.provide(Server.defaultWith(_.port(9000).gracefulShutdownTimeout(30.seconds)))
}

The platform has its own clock. docker stop sends SIGTERM and, if the container is still running 10 seconds later, SIGKILL; Kubernetes waits for the pod's terminationGracePeriodSeconds, which is 30 seconds unless you set it. Give the platform more time than the server's graceful shutdown timeout plus a few seconds for the steps after it: with the default 10-second timeout, docker stop can kill the server before its requests finish, so stop it with a longer wait, as in docker stop -t 30 <container>.

note

ZIOApp has a timeout of its own, ZIOApp#gracefulShutdownTimeout, which limits how long the shutdown hook waits for the layers to be released. Its default is Duration.Infinity, so the server's timeout is the one that applies. If you override it in your ZIOAppDefault, keep it longer than the server's timeout, or the JVM exits before the requests finish.

To see the shutdown without Docker, run the Graceful Shutdown example, which has a similar slow route.

Choosing Development or Production Mode​

ZIO HTTP reads its mode from the ZIO_HTTP_MODE environment variable, or from the zio.http.mode system property, which takes precedence. The values are dev, preprod, and prod. When neither is set, or the value is not one of these, the mode is prod, so a production container needs no setting at all.

The mode changes what an error response shows. In dev, an error response has a body: a 404 names the requested path, and a 500 for a defect includes the exception's stack trace. In prod and preprod, an error response has the status code and an empty body, so nothing about the server's internals reaches the client.

Mode.current returns the active mode. Logging it at startup makes the mode of a running container easy to check in its logs:

object ModeAwareServer extends ZIOAppDefault {
val run =
ZIO.logInfo(s"Starting in ${Mode.current} mode") *>
Server.serve(OrderRoutes.routes).provide(Server.configured())
}

You can also branch on Mode.isDev to add routes only in development; Dev / Preprod / Prod Modes shows how, and how to switch the mode in tests.

Building a Docker Image with sbt-native-packager​

sbt-native-packager builds the image from your sbt project, so you do not write a Dockerfile. Add the plugin to project/plugins.sbt:

addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.13.0")

Then enable it in build.sbt. JavaAppPackaging packages the application with a start script, and DockerPlugin wraps that package in an image. The image takes its name and tag from name and version:

name := "orders-service"
version := "1.0.0"
scalaVersion := "2.13.18"

libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

enablePlugins(JavaAppPackaging, DockerPlugin)

Compile / mainClass := Some("example.deploy.DeployableServer")
dockerBaseImage := "eclipse-temurin:21-jre"
dockerExposedPorts := Seq(8080)

dockerBaseImage picks the Java runtime the image is built on; ZIO HTTP needs Java 17 or newer. dockerExposedPorts documents the port the server listens on by default. Build the image into your local Docker:

sbt Docker/publishLocal

The result is the image orders-service:1.0.0. Its entry point is the start script, which replaces itself with the java process, so java is the only process in the container and the SIGTERM from docker stop reaches the JVM directly.

tip

sbt stage builds the same package without Docker, in target/universal/stage. Run it with target/universal/stage/bin/orders-service to try the start script and the environment variables on your machine.

Running and Stopping the Container​

Start a container on port 9000 with a 20-second graceful shutdown timeout:

docker run -d --name orders -p 9000:9000 \
-e ZIO_HTTP_SERVER_BINDING_PORT=9000 \
-e ZIO_HTTP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT=20s \
orders-service:1.0.0

Once the logs show Server started, the health check answers on the new port:

curl localhost:9000/health
OK

The startup log line from the previous section shows that the container runs in production mode:

timestamp=... level=INFO thread=#zio-fiber-470566940 message="Starting in Prod mode" location=example.deploy.DeployableServer.run file=DeployableServer.scala line=31

Now we stop the container while a request is in flight. In one terminal, request the slow report:

curl localhost:9000/report

Within five seconds, stop the container from a second terminal, with a wait longer than the server's timeout:

docker stop -t 30 orders

The server stops accepting connections but finishes the report, so the first terminal still prints:

Report ready

docker stop returns a few seconds after the report is delivered, once the server has shut down. To see the development mode instead, start the container with -e ZIO_HTTP_MODE=dev and request a path that does not exist: the 404 response then has an HTML body naming the path, where in production mode its body is empty.

Putting It Together​

The complete server combines the routes, the Server.configured() layer, and the startup log line from the sections above. It differs from the earlier snippets in three ways: the routes are defined directly in the DeployableServer object instead of in OrderRoutes, the object lives in the example.deploy package, and a single run logs the mode and then serves the routes. It is the example.deploy.DeployableServer that the build.sbt above names as its main class:

zio-http-example/src/main/scala/example/deploy/DeployableServer.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
// Run from this folder: scala-cli run DeployableServer.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.deploy.DeployableServer"

package example.deploy

import zio._

import zio.http._

/**
* Package and Deploy a ZIO HTTP Server — the complete server
*
* The server reads its settings from the environment with
* `Server.configured()`, for example `ZIO_HTTP_SERVER_BINDING_PORT=9000` or
* `ZIO_HTTP_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT=30s`, and logs the mode chosen by
* `ZIO_HTTP_MODE`. On SIGTERM it stops accepting connections and lets the
* in-flight requests finish, so a `GET /report` sent just before `docker stop`
* still gets its response.
*/
object DeployableServer extends ZIOAppDefault {

val routes: Routes[Any, Response] =
Routes(
Method.GET / "health" -> handler(Response.text("OK")),
Method.GET / "report" -> handler(ZIO.sleep(5.seconds).as(Response.text("Report ready"))),
)

val run =
ZIO.logInfo(s"Starting in ${Mode.current} mode") *>
Server.serve(routes).provide(Server.configured())
}

Running the Examples​

The complete example is zio-http-example/src/main/scala/example/deploy/DeployableServer.scala. Run it from that folder with scala-cli run DeployableServer.scala, or from the repository root with sbt "zioHttpExample/runMain example.deploy.DeployableServer". Set the environment variables from this guide in the same shell to change its port, timeout, or mode.

Going Further​