Docker
In this section, we'll see how to deploy a Ktor application to a Docker container, which can then be run either locally or on your cloud provider of choice.
Docker is a container system that allows for packaging software in a format that can then be run on any platform that supports Docker, such as Linux, macOS, and Windows. Conceptually Docker is an operating system with layers providing multiple services. While the basics of Docker will be covered, if you're not familiar with it, check out the Getting Started documentation.
Clone a sample application
In this tutorial, we'll be using a project created in Creating a new Ktor project: ktor-get-started-sample.
Get the application ready
In order to run on Docker, the application needs to have all the required files deployed to the container. As a first step, you need to create a fat JAR file containing the application and its dependencies. Depending on the build system you're using, there are different ways to accomplish this:
To prepare a Gradle project, follow the steps from the Configure the Shadow plugin section.
To prepare a Maven project, follow the steps from Configure the Assembly plugin.
Prepare Docker image
To dockerize the application, we'll use multi-stage builds:
First, we'll use the
gradle
/maven
image to generate a distribution of the application.Then, the generated distribution will be run in the environment created based on the
openjdk
image.
In the root folder of the project, create a file named Dockerfile
with the following contents:
The second stage of the build works in the following way:
Indicates what image is going to be used (
openjdk
in this case).Specifies the exposed port (this does not automatically expose the port, which is done when running the container).
Copies the contents from the build output to the folder.
Runs the application (
ENTRYPOINT
).
Build and run the Docker image
The next step is to build and tag the Docker image:
Finally, start the image:
If using IntelliJ IDEA, you can click Run
in the Dockerfile
to perform these steps:

Learn more from the Docker topic.