In this topic, we'll show how to run a server Ktor application under Docker Compose. We'll be using a project created in Database persistence with Exposed, which uses Exposed to connect to an H2 file database. In this topic, we'll replace H2 with a PostgreSQL database running as a separate
db service, while the Ktor application will be running as a
Get the application ready
Add PostgreSQL dependency
First, you need to add dependencies for the PostgreSQL library. Open the
gradle.properties file and specify library versions:
build.gradle.kts and add the following dependencies:
Connect to a database
The tutorial-website-interactive-persistence sample uses hardcoded
jdbcURL in the
com/example/dao/DatabaseSingleton.kt file to establish a database connection. Let's extract connection settings for the PostgreSQL database to a custom configuration group. Open the
src/main/resources/application.conf file and add the
storage group outside the
ktor group as follows:
jdbcURL includes the following components:
db:5432is a host and port on which the PostgreSQL database is running.
ktorjournalis the name of the database created when running services.
These settings will be configured later in the docker-compose.yml file.
com/example/dao/DatabaseSingleton.kt and update the
init function to load storage settings from the configuration file:
init function now accepts
ApplicationConfig and uses
config.property to load custom settings.
com/example/Application.kt and pass
DatabaseSingleton.init to load connection settings on application startup:
Configure the Ktor plugin
In order to run on Docker, the application needs to have all the required files deployed to the container. Depending on the build system you're using, there are different plugins to accomplish this:
For example, to apply the Ktor plugin, open the
build.gradle.kts file and add the
ktor plugin to the
Prepare Docker image
To dockerize the application, create the
Dockerfile in the root of the project and insert the following content:
Note that this
Dockerfile requires creating a fat JAR before running
docker compose up. To learn how to use multi-stage builds to generate an application distribution using Docker, see Prepare Docker image.
Configure Docker Compose
docker-compose.yml in the root of the project and add the following content:
webservice is used to run the Ktor application packaged inside the image.
dbservice uses the
postgresimage to create the
ktorjournaldatabase for storing articles of our journal.
Build and run services
docker compose up, create a fat JAR containing a Ktor application:./gradlew :tutorial-website-interactive-docker-compose:buildFatJar
docker compose up...docker compose --project-directory snippets/tutorial-website-interactive-docker-compose up
... and wait until Docker Compose pulls/builds the images and starts containers. You can open
http://localhost:8080/in a browser to create, edit, and delete articles.