Java

Deploy a Java App

This guide explains how to deploy a Java application to Koyeb using Git-driven or Docker-based deployment. The application can be built using either native buildpacks or from a Dockerfile.

To successfully follow this documentation, you will need to have a Koyeb account (opens in a new tab). You can optionally install the Koyeb CLI if you prefer to follow this guide without leaving the terminal.

You can deploy and preview the Java application from this guide using the Deploy to Koyeb button below.

Deploy to Koyeb (opens in a new tab)

You can consult the repository on GitHub (opens in a new tab) to find out more about the example application that this guide uses.

Create the Java app

Get started by creating a minimalistic Java application that we will deploy on Koyeb. You will need Java (opens in a new tab) installed on your machine as well as Maven (opens in a new tab) to manage dependencies and build your project.

Generate a basic application

In your terminal, run the following commands to create a new project directory from a basic template (opens in a new tab):

mvn archetype:generate -DgroupId=app.koyeb.example \
    -DartifactId=example-java \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DarchetypeVersion=1.4 \
    -DinteractiveMode=false

This command generates a project directory with a pom.xml file for managing project dependencies, properties, and metadata. It also generates a single class file in src/main/java/app/koyeb/example/App.java. The configuration we passed to the command created a project using app.koyeb.example as the group ID and example-java as the artifact ID.

Enter the new directory structure to get start:

cd example-java

You can compile the generated sample application by typing:

mvn package

After building, you can test the default application by typing:

java -cp target/*.jar app.koyeb.example.App

The application will display "Hello World!" as an output.

Create a hello world web app

While the generated application produces output for the command line, we want to make an application that responds to web requests.

To do this, we need to replace the main application class. Open the example-java/src/main/java/app/koyeb/example/App.java file in your text editor. Replace the current contents with the following code:

example-java/src/main/java/app/koyeb/example/App.java
package app.koyeb.example;
 
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
 
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
 
public class App {
 
  public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8888"));
    HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
    server.createContext("/", new MyHandler());
    server.setExecutor(Executors.newCachedThreadPool());
    System.out.println("Listening on port " + port + ".");
    server.start();
  }
 
  static class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {
      String response = "Hello world!";
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
  }
}

The new code imports functionality from various packages and classes to help us create a basic web server. We replace the main App class with one that creates a server that responds to requests at / with "Hello world!". By default, it listens on port 8888, but this can be overridden by setting the PORT environment variable to a different value.

Test the new web application implementation by building and running the executable again:

mvn package
java -cp target/*.jar app.koyeb.example.App

If you visit localhost:8888 in your web browser, you should see the "Hello world!" message you configured.

Test that the port is configurable by running the same command again with the PORT environment variable set:

PORT=5555 java -cp target/*.jar app.koyeb.example.App

Now, instead of being served on port 8888, the application will be accessible at localhost:5555.

Configuring the project

Next, we'll modify the project a bit more to make it easier to run.

Open the pom.xml file in the project's root directory. Inside find the entries for the maven-jar-plugin plugin. Add a configuration section within the plugin specification to identify the main class of the application:

pom.xml
. . .
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
          <configuration>
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>app.koyeb.example.App</mainClass>
              </manifest>
            </archive>
          </configuration>
        </plugin>
. . .

This encodes the main class within the .jar file so that you no longer have to specify the class to execute at runtime.

Close the file when you are finished.

Test the maven-jar-plugin configuration by building the package again and executing the resulting .jar file without specifying a class:

mvn package
java -jar target/*.jar

The server should begin listening for connections as expected.

Create a Dockerfile for the project (Optional)

We can build and run our Java project on Koyeb using the native Java buildpack, but we can also optionally build from a Dockerfile for more control. To make it possible to build a container image for our application, we just need to create the Dockerfile. We'll also define a .dockerignore file to tell the builder what files to skip when creating the image.

To leverage our Maven build configuration, generate a Maven wrapper that will let us include a Maven instance with our project:

mvn -N wrapper:wrapper

This generates a mvnw bash script, a mvnw.cmd batch script, and a .mvn/wrapper directory to store the actual executable and configuration. We can use the mvnw script just like we would the regular mvn command and it will execute the commands using the local copy of Maven instead of relying on a system copy.

Next, define a .dockerignore file in your main project directory. Inside, paste the following contents:

.dockerignore
.git
.gitignore
Dockerfile
.dockerignore
target

This file tells Docker to not include Git files, the Docker files themselves, and any build artifacts placed in the target directory. This helps ensure that the image we build is not bloated and that the build completes faster.

Next, create a new file called Dockerfile within the main project directory. Inside, paste the following contents:

Dockerfile
# Build stage
FROM eclipse-temurin:17-jdk-alpine AS builder
 
WORKDIR /app
COPY . .
RUN ./mvnw package
 
# Run stage
FROM eclipse-temurin:17-jdk-alpine AS runner
 
WORKDIR /app
COPY --from=builder /app/target/*.jar .
 
CMD ["java", "-jar", "example-java-1.0-SNAPSHOT.jar"]

This Dockerfile uses a multistage build (opens in a new tab) to separate the build steps from the final image environment. This creates a more streamlined image and allows us to tightly control what files are included in the final image.

Both stages are based on the Alpine version of the eclipse-temurin image (opens in a new tab). The build stage copies all of the files over to the image and builds the package. The compiled artifact is then copied to the runtime image where it is executed directly with the java executable.

If you have Docker installed locally, you can build and test the image on your computer and optionally upload it to a registry. You can deploy container images from any container registry to Koyeb.

We can also build the Dockerfile directly from the repository when we deploy, which is useful as a way of automatically deploying when changes occur. We will demonstrate this method as one of the options in this guide.

Push the project to GitHub

In the project directory, initialize a new git repository by running the following command:

git init

Next, download a basic .gitignore file designed for Maven projects from GitHub:

curl -L https://raw.githubusercontent.com/github/gitignore/main/Maven.gitignore -o .gitignore

Finally, specify the Java runtime version to use so that the Koyeb Java buildpack executes the project with the correct version:

echo "java.runtime.version=17" > system.properties

Next, add the project files to the staging area and commit them. If you don't have an existing GitHub repository to push the code to, you can create a new one and run the following commands to commit and push changes to your GitHub repository:

git add :/
git commit -m "Initial commit"
git remote add origin git@github.com:<YOUR_GITHUB_USERNAME>/<YOUR_REPOSITORY_NAME>.git
git push -u origin main

Make sure to replace <YOUR_GITHUB_USERNAME>/<YOUR_REPOSITORY_NAME> with your GitHub username and repository name.

Deploy to Koyeb using git-driven deployment

Once the repository is pushed to GitHub, you can deploy the Java application to Koyeb. Any changes in the deployed branch of your codebase will automatically trigger a redeploy on Koyeb, ensuring that your application is always up-to-date.

To deploy the Java app on Koyeb using the control panel (opens in a new tab), follow the steps below:

  1. Click Create App in the Koyeb control panel.
  2. Select GitHub as the deployment option.
  3. Choose the GitHub repository and branch containing your application code. Alternatively, you can enter our public Java example repository (opens in a new tab) into the Public GitHub repository at the bottom of the page: https://github.com/koyeb/example-java
  4. Choose the builder for your project. We can use either a Dockerfile or buildpack for this repository.
  5. If you chose the buildpack builder, expand the Build and deployment settings and click the toggle associated with the Run command. In the field, enter java -jar target/example-java-1.0-SNAPSHOT.jar.
  6. Name your service, for example java-service.
  7. Name the App, for example example-java.
  8. Click the Deploy button.

A Koyeb App and Service will be created. Your application will be built and deployed to Koyeb. Once the build has finished, you will be able to access your application running on Koyeb by clicking the URL ending with .koyeb.app.

Deploy to Koyeb from a container registry

If you chose to build a container image for the Java application, you can optionally deploy the application from a container registry instead of from GitHub.

To deploy a pre-built Java container image on Koyeb using the control panel (opens in a new tab), follow the steps below:

  1. Click Create App in the Koyeb control panel.
  2. Select Docker as the deployment option.
  3. Choose the container image and tag from your registry and click Next to continue.
  4. Name your service, for example java-service.
  5. Name the App, for example example-java.
  6. Click the Deploy button.

A Koyeb App and Service will be created. The container image will be pulled from the container registry and a container will be deployed from it. Once the initialization is complete, you will be able to access your application running on Koyeb by clicking the URL ending with .koyeb.app.