Skip to content

Services

micartey edited this page Feb 10, 2025 · 4 revisions

Java Applications

The following example demonstrates how to configure a Java application as a service on nixos-server. This is useful for running Java applications as system services, such as web servers, without needing to manually manage the process.

{ ... }:

{
  imports = [
    # Adjust accordingly to point to the correct file of this repository
    ../services/java-application.nix
  ];

  services.javaApplication = {
    enable = true;
    services = [
      {
        serviceName = "my-custom-service";
        jarPath = "/etc/opt/hello/helloworld.jar";
        user = "helloworlduser";
        workingDirectory = "/var/lib/helloworld";

        # Optionally:
        # port = 8080;                             #Port to be allowed in the firewall.
        # javaPackage = pkgs.openjdk17;
        # enable = true; (default true)
      }
      {
        serviceName = "another-service";
        jarPath = "/etc/opt/another/another.jar";
        user = "anotheruser";
        workingDirectory = "/var/lib/another";
        port = 9090;
        javaPackage = pkgs.openjdk11;
      }
    ];
  };

  environment.etc."opt/hello/helloworld.jar".source = ../dots/HelloWorld.jar;
  environment.etc."opt/another/another.jar".source = ../dots/Another.jar;
}

Setup

The service needs to be registered in /hosts/default.nix. This particular example has the following 2 assumptions:

  1. There is a JAR file named HelloWorld.jar directly under the dots directory.
  2. The service definition is located directly in hosts directory.

Clone this wiki locally