Skip to main content

Containers

Overview​

You can run a full Genesis application in a self-contained Docker container. There are two simple ways:

  • using our helpful plugin
  • by creating the Dockerfile and image yourself

Prerequisites​

Building​

The Genesis Application Platform provides two different options for building a Docker image.

  • The first option, which is covered in this section, is using the Gradle plugin. This is the easiest and quickest way to get up and running with a Docker image, but it comes with the cost of reduced flexibility. This option is highly recommended for new developers to try Genesis out.

  • The second option is to create your own Dockerfile and build your own image. This provides the most flexibility, but it means you need to manage the Genesis dependencies yourself.

Gradle plugin overview​

The Gradle plugin provides the easiest and quickest way to get Genesis running in a Docker container. We provide a Gradle task that generates a Dockerfile for you, with all the necessary dependencies, and then builds it.

The plugin provides three main Gradle tasks to help you build your Docker image:

  • createDockerfile - generates the Dockerfile dynamically based on user-defined settings and dependencies. It writes the Dockerfile to build/docker/ in the module that applies the plugin, and copies all the files needed for the context into that folder.
  • buildImage - runs createDockerfile as a sub-task, and then runs docker build on the generated Dockerfile.
  • pushImage - pushes the generated image to a repository defined in gradle.properties (see section on pushing).

The plugin also registers a debug variant of each of these tasks:

  • createDebugDockerfile - the debug equivalent of createDockerfile. It generates the Dockerfile and its context in build/docker-debug.
  • buildDebugImage - the debug equivalent of buildImage.
  • pushDebugImage - the debug equivalent of pushImage.

buildDebugImage builds an image called <product>-debug:<version> in build/docker-debug, rather than <product>:<version>. Compared with the image from buildImage, the debug image:

  • installs openssh-server, sets the login credentials to genesis:genesis and starts sshd;
  • copies the plugin's dev-data/ folder into /app/dev-data.

Using the plugin​

  1. Create or use an existing Genesis project.

  2. Make the necessary changes to the genesis-system-definitions.kts for your dependencies, such as the location of the database.

tip

Step 3 is required. A newly created project does not set genesisDeploy.enabled for you, so add it yourself before you run buildImage.

  1. Set genesisDeploy.enabled = true in your server/settings.gradle.kts within the genesis plugins section. This step is required before you run buildImage. For example:
genesis {
productName = "appname"

dependencies {
dependency("global.genesis:auth:${extra.properties["authVersion"]}")
dependency("global.genesis:fix:${extra.properties["genesisFixVersion"]}")
}
plugins {
genesisDeploy.enabled = true
}
}

Without this setting, buildImage fails with Cannot expand ZIP ... as it does not exist. If you see that error, check that the flag is set. When the flag is set, Gradle prints a deprecation warning for genesisDeploy; this is expected in 10.0 and you can ignore it.

  1. Ensure the client is included in the image by adding the following to server/settings.gradle.kts. Do this only if your project has a web client in client/; leave it out for a server-only project:
includeBuild("../client")
  • Additionally, make sure that the client/build.gradle.kts file has group specified; add the following to the root of the file:
group = "global.genesis"
  • Then add the following to the dependencies block in your build.gradle.kts within the app module (for example, server/example-app/build.gradle.kts). Again, only if your project has a web client in client/; leave it out for a server-only project:
genesisWeb("global.genesis:client")
  1. Run the buildImage Gradle task from the root of the server/ project. You can also run this task from your IDE if you prefer:
./gradlew buildImage
tip

If you're unable to execute the gradlew command, ensure you have the correct permissions on the file. Add execute permissions with chmod +x gradlew

The gradle buildImage command requires connection to Docker/Rancher, which should be running locally. If you're running Rancher on Mac, you may need to run the following socat image, which enables you to build your Genesis application image:

docker run -d --restart always -v /var/run/docker.sock:/var/run/docker.sock -p 2375:2375 --name socat rycus86/docker-socat

Once the image has been built, the output should display the name of the image:

Successfully built eaa290495637
Successfully tagged genesis/appname:1.0.0-SNAPSHOT
Created image with ID 'eaa290495637'.

Running​

The container needs an external database. H2, the default for local development, is not supported inside the container: remap fails with No suitable driver. Point the container at PostgreSQL, MSSQL or Oracle. To get a starting point, see Generating a compose file: the writeGenesisDockerCompose task writes a compose file that starts a PostgreSQL service and configures the Genesis services to use it.

If you haven’t already initialised the database, you can run the Docker container passing the environment variable GENESIS_DB_INSTALL=true. This triggers a remap to create all the tables and will exit on completion.

docker run -e GENESIS_DB_INSTALL=true genesis/appname:1.0.0-SNAPSHOT

You can then start the Docker container with whichever system you choose to use (e.g. docker-compose / Kubernetes etc.) Or you can run the container on its own, for example:

docker run -it -p 443:443 genesis/appname:1.0.0-SNAPSHOT

To run it detached instead, use docker run -dit -p 443:443 genesis/appname:1.0.0-SNAPSHOT.

Note: The -p flag is used in this example, as nginx is bundled in with our image and presents the Genesis app on port 443.

info

The Genesis startup script needs a pseudo-TTY, so whatever runs the container must allocate one. Without it, the startup script will not behave as expected. In Docker Compose, set tty: true on the service. In Kubernetes, the equivalent is not needed as the pod lifecycle is managed differently — use the health probes described below instead.

info

The Genesis router requires an Accept: application/json header on all HTTP requests. Requests made without this header return 406 Not Acceptable. This applies to the health endpoints as well as any application API calls. Most HTTP clients (for example, curl) send an appropriate Accept header by default, but if you are calling the router from code, ensure you set this header explicitly.

curl -H "Accept: application/json" http://localhost:9064/my-endpoint

Dockerfile​

If you want more control over the image, you can create your own Dockerfile. This gives you complete control over the base image and the versions of the underlying dependencies.

There are quite a few configuration steps and dependencies that are required as part of the image build. Below is a simplified example to illustrate the typical steps; it is not the file the Gradle task generates, which is more detailed and changes between releases. You will need to manage the locations of the dependencies for copying to the container. If the dependencies are remote, you might need to use wget or a similar tool. To see the current generated Dockerfile, run ./gradlew createDockerfile from the root of the server/ project and open the file it writes to build/docker/ in the module that applies the plugin (usually your app module, for example server/<app>-app/build/docker/).

FROM rockylinux:8
RUN yum install -y unzip ncurses python3 java-17-openjdk-devel lmdb-libs openssl nginx procps
RUN ln -s /usr/lib64/liblmdb.so.0.0.0 /usr/lib64/liblmdb.so
RUN update-alternatives --set python /usr/bin/python3
RUN mkdir -p /app/run/site-specific/cfg /app/web/console /etc/ssl/certs
RUN openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout /etc/ssl/certs/certs.key -out /etc/ssl/certs/certs.pem -subj "/C=GB/L=London/O=Genesis Global/CN=localhost"
WORKDIR /app
COPY nginx.conf /etc/nginx/nginx.conf
RUN echo "export GENESIS_HOME=/app/run/" >> ~/.bashrc
RUN echo "source \$GENESIS_HOME/genesis/util/setup.sh" >> ~/.bashrc
COPY genesis-distribution-6.2.0-SNAPSHOT-bin.zip /app
RUN unzip genesis-distribution-6.2.0-SNAPSHOT-bin.zip -d run/
RUN rm -f genesis-distribution-6.2.0-SNAPSHOT-bin.zip
COPY auth-distribution-6.2.0-SNAPSHOT-bin.zip /app
RUN unzip auth-distribution-6.2.0-SNAPSHOT-bin.zip -d run/
RUN rm -f auth-distribution-6.2.0-SNAPSHOT-bin.zip
COPY log4j2-default.xml /app/run/site-specific/cfg/
COPY web-distribution.zip /app
RUN unzip web-distribution.zip -d web/
RUN rm -f web-distribution.zip
COPY position-site-specific-1.0.0-SNAPSHOT-bin.zip /app
RUN unzip position-site-specific-1.0.0-SNAPSHOT-bin.zip -d run/
RUN rm -f position-site-specific-1.0.0-SNAPSHOT-bin.zip
COPY genesisproduct-position-1.0.0-SNAPSHOT-bin.zip /app
RUN unzip genesisproduct-position-1.0.0-SNAPSHOT-bin.zip -d run/
RUN rm -f genesisproduct-position-1.0.0-SNAPSHOT-bin.zip
RUN source ~/.bashrc && genesisInstall --ignoreHooks
RUN source ~/.bashrc && preCompileScripts
SHELL ["bash", "-c"]
ENV GENESIS_SYSDEF_BlockGenesisInstall=true
EXPOSE 8080
EXPOSE 443
CMD ["/app/run/genesis/util/dockerStartup.sh", "-p"]

The Dockerfile that the Gradle plugin generates sets GENESIS_SYSDEF_BlockGenesisInstall=true in the final image, so genesisInstall does nothing in a running container. The genesisInstall step that runs while the image is built isn't affected. If you supply your own Dockerfile through the customDockerfile setting, this line isn't added for you.

The preCompileScripts step compiles the .kts scripts into the script cache while the image is built. To compile them during the Gradle build instead, see Build-time script compilation.

Pushing​

If you choose to use the Gradle plugin to build the image, the Genesis Application Platform provides a Gradle task that pushes your built image to your chosen repository.

To configure this task, add the following settings to your gradle.properties:

NameDescription
dockerUrlThe URL to the repository you wish to push to
dockerUsernameUsername
dockerPasswordPassword
dockerEmailEmail address

Healthchecks​

The Genesis Application Platform Docker image provides a health check endpoint, which reports the status of the container.

This endpoint can be used for your liveliness/readiness checks if you are using container orchestration, or you can use it in your own checks if you are managing your containers yourself.

PathPortResponse
/health/statusThis is set in the System Definition with the item DaemonHealthPort and an integer value for the port chosen to serve the health status

Example: item(name = "DaemonHealthPort", value = "4569")
Either 200 for HEALTHY or 503 for UNHEALTHY if ANY of the underlying services are not in a healthy state.

The payload of the response is a JSON array and provides details for each underlying service configured in the container, including their individual health status
info

It is normal for /health/status to return 503 during startup while processes are initialising. This does not indicate a problem — it simply means the services have not yet reached a HEALTHY state. Allow sufficient startup time before treating a 503 as a failure (use initialDelaySeconds or a startup probe in Kubernetes).

Note: You need to ensure the port is accessible with the Docker --port option; alternatively, check the documentation for whichever container orchestration system you use.

Sample response​

This is an example only. The processes and ports in your response depend on your configuration.

[
{
"PROCESS_NAME":"GENESIS_AUTH_MANAGER",
"STATUS":"UP",
"MESSAGE":"",
"PORT":8001
},
{
"PROCESS_NAME":"GENESIS_AUTH_DATASERVER",
"STATUS":"UP",
"MESSAGE":"",
"PORT":8002
},
{
"PROCESS_NAME":"GENESIS_AUTH_PERMS",
"STATUS":"UP",
"MESSAGE":"",
"PORT":8003
},
{
"PROCESS_NAME":"GENESIS_AUTH_REQUEST_SERVER",
"STATUS":"UP",
"MESSAGE":"",
"PORT":8004
},
{
"PROCESS_NAME":"GENESIS_AUTH_CONSOLIDATOR",
"STATUS":"UP",
"MESSAGE":"",
"PORT":8005
},
{
"PROCESS_NAME":"GENESIS_CLUSTER",
"STATUS":"UP",
"MESSAGE":"",
"PORT":9000
},
{
"PROCESS_NAME":"GENESIS_ROUTER",
"STATUS":"UP",
"MESSAGE":"",
"PORT":9017
},
{
"PROCESS_NAME":"GENESIS_NOTIFY",
"STATUS":"UP",
"MESSAGE":"",
"PORT":9018
}
]

Process health endpoints​

A process that uses the WEBSOCKET messaging channel also serves its own health endpoints on its own port, which is the port in its service definition entry, unless you override it with the {PROCESS_NAME}_PORT environment variable. Processes on the default TCP channel don't have these endpoints. To set the channel for every process, add this to network-config.yaml, or to network-config-<PROCESS_NAME>.yaml for a single process. In your project's source tree, put the file in the application module's src/main/genesis/cfg/ folder; because its name doesn't start with your product name, the build packages it into $GENESIS_HOME/site-specific/cfg (/app/run/site-specific/cfg in the image above), which is where the process reads it:

messaging:
channel: WEBSOCKET

After adding or changing the file, rebuild the project, run genesisInstall, then restart the process for the change to take effect.

All the endpoints accept GET. A status value is the process state, so besides UP and DOWN you can see STARTING, STANDBY and WARNING.

PathResponse
/health{"status":"<state>"}. 503 when the state is DOWN, ERROR or UNKNOWN; otherwise 200
/health/detailsThe state plus each monitor's status and, where there is one, its message, under components. Same status codes as /health
/health/readiness{"status":"UP"} or {"status":"OUT_OF_SERVICE"}, with the cluster's readiness and the process state under details. 200 only when the cluster is ready and the state is UP or WARNING; otherwise 503
/prometheusMetrics in Prometheus text format. Only present when the PROMETHEUS reporter is enabled

A STANDBY process, such as the secondary node of a cluster, is reachable but not taking work. It returns 200 on /health and 503 on /health/readiness, so a readiness probe sends it no traffic.

These endpoints don't require authentication: anyone who can reach the process's port can read them, including monitor messages and metrics. The router doesn't forward them, so you can't reach them through the router's port. Restrict access to process ports in your deployment.

Configuration options​

Docker plugin extension​

To customize how the Docker plugin behaves, the Genesis Application Platform provides a Gradle plugin extension.

The table below describes the values that can be changed:

NameDescriptionDefault
compactProcessesWhen set to true, combines compatible services into a single process, which reduces the number of services running within the containerfalse
compactProcessesStrategySets the strategy used when compactProcesses is enabled.DEFAULT
propagateSysDefEnvVarsInDockerFileWhen set to true, sets all GENESIS_SYSDEF_ environment variables that are available at build time in the Dockerfile.
This allows template processing when genesisInstall is executed, and default values to be pre-set during the build.
false
customDockerfileThe path to a Dockerfile that overrides the generated Dockerfile for the main image.Not set
customDebugDockerfileThe path to a Dockerfile that overrides the generated Dockerfile for the debug image.Not set
useGenesisContainerLogConfigDefines whether the container should use a specific log4j configuration file that is designed for our containers.
When set to true, logs are effectively output by the container PID1, allowing most container orchestration systems to capture all the logs with default settings.
true
preCompileScriptsWhen set to true, the generated Dockerfile includes a step that compiles every .kts script into the script cache during the image build.
This results in a slower build process, but dramatically decreases the start-up time of the container.
See also Build-time script compilation.
true

preCompileScripts and compileScriptsAtBuildTime are independent, and it is safe to have both turned on. The image build still compiles every script into the script cache, and at start-up the platform uses the scripts compiled at build time first, falling back to the cache. Once your scripts are compiled at build time, you can set preCompileScripts to false to make the image build faster.

These settings should be set in the build.gradle.kts file of your app module (for example, server/example-app/build.gradle.kts), where the Genesis exec plugin is applied. The dockerImage extension is not available in server/build.gradle.kts.

dockerImage {
compactProcesses.set(true)
}

To build a debug image, use the separate buildDebugImage task.

Local plugin configuration​

The Genesis Application Platform also supports overriding the Docker registry credentials (dockerUrl, dockerUsername, dockerPassword and dockerEmail), allowing for different values for different environments. This means that you can set your own values without changing any files that are tracked in SCM. No other dockerImage setting can be overridden this way.

This is done by adding server/gradle.properties and ensuring that the file is ignored by SCM.

Only the registry credentials can be supplied as Gradle properties: dockerUrl, dockerUsername, dockerPassword and dockerEmail, each set as a Gradle property of the same name (for example, in server/gradle.properties). The other dockerImage settings must be set in the dockerImage block.

Environment variables​

Below is a list of environment variables that can be passed to the Docker container at runtime.

VariableDescriptionDefault
GENESIS_DB_DRY_RUNAllows you to see the output of a remap without committing it.
This option only has an effect if it’s used with GENESIS_DB_INSTALL or GENESIS_DB_UPGRADE
false
GENESIS_DB_INSTALLRuns a remap and then a genesisInstallHooks --init to mark the migration hooks so they do not run again.
This should only be used during the initial DB setup, as it will ignore the migration hooks.
GENESIS_DB_UPGRADE should be used for any further DB schema changes.
The container will exit on completion and will not run any Genesis processes.
false
GENESIS_DB_UPGRADERuns genesisInstallHooks to run any migration hooks, then runs a remap
The container will exit on completion and will not run any Genesis processes
false
GENESIS_SYSDEF_BlockGenesisInstallStops genesisInstall from running in the container. Set it to false to run genesisInstall in a container anywaytrue in images generated by the Gradle plugin

You can also set System Definitions values from environment variables, which allows you to change the location of external dependencies (such as the database) between your production and non-production environments.

Clustering​

The Genesis Application Platform is highly resilient and easy to cluster for a High Availability (HA) setup.

This area takes you through how to configure the platform with our clustering options when using containers.

Built-in clustering​

Built-in clustering uses Apache Pekko to manage the members of the cluster. It is the LEGACY cluster mode, and it is the default: a host uses it when ClusterMode is not set. For how it works, including the hosts list and setting the primary node, see clustering for virtual machines.

In a container, set the mode with the GENESIS_SYSDEF_ClusterMode environment variable:

GENESIS_SYSDEF_ClusterMode: LEGACY

In LEGACY mode, choose the primary node by setting GENESIS_PRIMARY: "true" on exactly one app service. The image's start-up script then runs SetPrimary when that container starts. Without it, every node starts as SECONDARY and primaryOnly processes never start.

GENESIS_PRIMARY: "true"

In this mode, the hosts must be able to reach each other on ClusterPort (6000 by default). See Networking.

Generating a compose file​

To get a starting docker-compose.yml, run the writeGenesisDockerCompose task from the root of the server/ project. The task comes with the Genesis Exec plugin (global.genesis.exec), and it writes the file to build/docker-compose/docker-compose.yml in your app's main module. The generated file runs one app container, which uses the image built by buildDebugImage, alongside a PostgreSQL database and one-off containers that create the tables and load the dev data.

The generated compose file always uses the debug image, which has SSH enabled with fixed credentials and includes dev data. It is intended for local development, not for deployment. The compose extension's build task depends on buildDebugImage.

./gradlew writeGenesisDockerCompose

For a two-node cluster, copy the app service and give each copy its own settings. The generated file sets GENESIS_SYSDEF_ClusterMode: LEGACY, which is built-in clustering. In that mode, no GENESIS_SYSDEF_* setting differs between nodes. Instead, give each app container its own hostname, and list all of those hostnames together in the hosts list of one system block in your system definition. In this mode the hosts list is also the cluster membership list, so each node needs a distinct hostname.

An app chooses its environment in the system definition by matching its own hostname against the host(...) entries. A host(LOCAL_HOST) block matches any container, and it must be the last system block. That is how the generated compose file works without setting hostname: on the app container.

A node matched by host(LOCAL_HOST) runs with that block's environment. For example, in a genx-generated system definition that lists explicit hosts under PROD and then has DEV with host(LOCAL_HOST), any unlisted container gets the DEV values. To run as an environment whose block lists explicit hosts, the container's hostname: must match one of those hosts.

For Consul mode, a host(LOCAL_HOST) system block is enough, and no per-container hostname: is needed. Change GENESIS_SYSDEF_ClusterMode to CONSUL on both nodes, and give each node a stable identity for its node ID claim with ConsulNodeName:

# node 1
GENESIS_SYSDEF_ClusterMode: CONSUL
GENESIS_SYSDEF_ConsulNodeName: node-1

# node 2
GENESIS_SYSDEF_ClusterMode: CONSUL
GENESIS_SYSDEF_ConsulNodeName: node-2

If a node's Consul agent is not on localhost, also set GENESIS_SYSDEF_ConsulHostAddress for that node. See extended configuration.

Running Consul and an MQTT broker​

The generated file doesn't include Consul or an MQTT broker. Add them as services alongside the app nodes. This fragment is for development and testing: it runs a single Consul agent in dev mode, which keeps no data when it stops, and a Mosquitto broker that accepts anonymous connections. For production, use a Consul cluster with an agent on each host, and a broker that is secured and hosted separately. See Prerequisites.

services:
consul:
image: hashicorp/consul:1.20.2
command: agent -dev -client=0.0.0.0
ports:
- "8500:8500"

mosquitto:
image: eclipse-mosquitto:2.0.20
ports:
- "1883:1883"
volumes:
- ./mosquitto.conf:/mosquitto/config/mosquitto.conf:ro

Mosquitto 2.x only accepts connections from its own container unless you configure a listener, so create a mosquitto.conf next to the compose file:

listener 1883
allow_anonymous true

Then point each app node at them, with the same settings on every node. ConsulHostAddress and ConsulHostPort are described in extended configuration, and MqLayer and MqttBrokerUrl in MQTT configuration options:

GENESIS_SYSDEF_ConsulHostAddress: consul
GENESIS_SYSDEF_MqLayer: MQTT
GENESIS_SYSDEF_MqttBrokerUrl: tcp://mosquitto:1883

The service names consul and mosquitto are the hostnames the app containers use on the compose network. Add depends_on entries for both services to the app nodes if you want them to start first.

The app image does not include the consul binary. Run consul commands, such as the consul kv get and consul catalog commands in Node IDs, in the Consul container, for example docker compose exec consul consul kv get -recurse genesis/cluster/<name>/node-ids/. Alternatively, call Consul's HTTP API on port 8500, for example /v1/kv/genesis/cluster/<name>/node-ids/?recurse.

Consul​

The Consul cluster mode uses Hashicorp's Consul for service discovery.

Combining this with the use of an MQTT broker gives you a dynamically scalable Genesis app with automatic failover.

Prerequisites​

Services​

To operate the Genesis Application Platform within an HA setup using Hashicorp's Consul for Clustering, the following services must be available:

  • A Database - A database needs to be hosted independently from the platform
  • A Consul Cluster - A Consul cluster with an agent on each of the hosts running a Genesis app
  • An MQTT Broker - Any message queue broker that supports MQTT, such as Mosquitto or RabbitMQ
important

The Genesis Application Platform can run with Consul without MQTT using ZeroMQ.

However, this is not recommended as MQTT is required for dynamic scaling.

Automatic failover​

When Consul is used, processes that are set to primaryOnly failover automatically to the secondary node when the primary node becomes unresponsive. (Failover must be performed manually if you are using the standard Genesis Clustering service.)

Each primaryOnly process competes for a leader lock in Consul, held through a Consul session. The process that holds the lock is the primary. A primary demotes itself and shuts down when either of these happens:

  • another session takes the lock, or the lock is released or removed
  • it has had no successful contact with Consul for ConsulLeaderContactDeadlineSeconds

When a session ends, Consul keeps the lock from every other session for ConsulSessionLockDelaySeconds, so that the old primary has stopped before a secondary takes over. A demoted process that has not shut down within its grace period is halted. The grace period is ConsulOrderlyHaltGraceSeconds, or ConsulLostContactHaltGraceSeconds if the process demoted itself because it lost contact with Consul.

A process that calls a service through MessageService also fails over. If the service replies with an UNAVAILABLE NACK, MessageService resolves the service again and retries until the request times out, and the calling process reports a WARNING state until the service replies. If the time runs out, the caller receives the last UNAVAILABLE NACK.

Networking​

All Genesis services within an app need to be able to access all the other Genesis services in the cluster on their defined ports. This applies to both built-in clustering and Consul mode.

When using built-in clustering (ClusterMode is LEGACY), the hosts must also be able to reach each other by host name and on ClusterPort (6000 by default). ClusterPort is not used when ClusterMode is CONSUL, so it does not need to be opened between hosts.

Service ports are configured, not fixed. Each process's port is set in its service definitions (<app>-service-definitions.xml) and can be overridden per deployment. For example, the auth service's definitions ship as auth/cfg/auth-service-definitions.xml in the auth distribution. To see the ports in use, run mon on a running node, or read the deployed service definitions. Every service port listed there must be reachable between the hosts in the cluster.

When MqLayer is ZeroMQ and the ZeroMQ proxy is not used (ZeroMQProxyModeEnabled is false, which is the default), each service also listens on its port plus 10000; for example, a service on port 9000 also listens on 19000. Those ports must also be reachable between hosts.

When the ZeroMQ proxy is used, the processes that use GENESIS_CLUSTER as a proxy for the update queue use these system definition items:

System definition itemPort
ZeroMQProxyOutboundPort5000
ZeroMQProxyInboundPort5001

ZeroMQProxyOutboundPort (5000) must be reachable between hosts when ZeroMQProxyModeEnabled is true and ZeroMQProxyUnicastRelayEnabled is false. ZeroMQProxyInboundPort (5001) is only used on the local host. When ZeroMQProxyUnicastRelayEnabled is true, traffic between nodes goes to the GENESIS_CLUSTER service port instead.

See service definitions for information on how to set the ports for user-defined services, and how to override the ports dynamically.

When using Consul mode, the Consul Agents must also be able to access all the services on their defined ports.

Configuring the app​

Basic configuration​

If a Consul agent is running locally to the app on the default port of 8500, then the only config required is:

genesis-system-definition.kts
systemDefinition {
global {
...
item(name = "ClusterMode", value = "CONSUL")
...
}
}

Extended configuration​

ItemDescriptionDefault
ConsulHostAddressIP or hostname of the Consul Agentlocalhost
ConsulHostPortHTTP Port for the Consul Agent8500
ConsulConnectionTimeoutSecondsSet the timeout for connecting to the Consul Agent in seconds10
ConsulReadTimeoutSecondsSet the timeout for reading from the Consul Agent in seconds10
ConsulWriteTimeoutSecondsSet the timeout for writing to the Consul Agent in seconds10
ConsulWatchSecondsHow long to tell the Consul server to wait for new key/value cache values8
ConsulTtlSecondsTimeout for the TTL Consul checks15
ConsulTtlPingSecondsHow often to run the TTL checks and update Consul with the stateConsulTtlSeconds / 2
ConsulDeregisterTimeoutMinsTime to wait after a TTL check goes critical before it deregisters the service in minutes30
ConsulSessionLockDelaySecondsHow long Consul keeps the leader lock from other sessions after a session ends, in seconds. The maximum is 60. Values from 1 to 24 are raised to 25. 0 turns off the delay, so a demoted primary is no longer guaranteed to have stopped before a secondary is promoted25
ConsulLeaderContactDeadlineSecondsHow long a primary can go without successful contact with Consul before it demotes itself, in seconds. The minimum is 15ConsulSessionLockDelaySeconds - ConsulLostContactHaltGraceSeconds - 5, and at least 15
ConsulLostContactHaltGraceSecondsHow long a process that demoted itself after losing contact with Consul has to shut down before it is halted, in seconds. The minimum is 15
ConsulOrderlyHaltGraceSecondsHow long a process demoted for any other reason has to shut down before it is halted, in seconds. The minimum is 1ConsulSessionLockDelaySeconds - 8, and at least 17
ClusterServiceAffinityGroupGroup services for preferred routing based on this value. Useful for multi-region set-ups""
ConsulServiceNamePatternAllows you to template your Consul service names with {{PROCESS_NAME}} eg. my_app_{{PROCESS_NAME}}null
ConsulNamespaceFormatSets Consul namespace (only used in Consul Enterprise)null
ConsulNodeNameThe host's identity in Consul, used for its node ID claim. Set a stable value in containersthe hostname
GFlakeNodeIdGraceMinutesHow long a node ID claim can go without a refresh before another host may take it, in minutes. Also sets how long a process tolerates Consul being unreachable. See heartbeat and grace period30
GFlakeNodeIdClusterNameThe name under which node IDs are claimed in Consul. Apps that share a database must use the same valuethe deployed product name
GFlakeNodeIdExplicitSet to true to use the NodeId in the system definition as a fixed node IDfalse

Node IDs​

Every record the platform writes gets a RECORD_ID from gFlake, which builds it from a timestamp, a node ID and a sequence number. The node ID keeps IDs from different hosts apart: two hosts with the same node ID can generate the same RECORD_ID.

In Consul mode, each host claims a unique node ID from Consul when its processes start, so you don't need to configure one. All processes on a host share the same claim, and a host that restarts gets its old ID back. This applies when ClusterMode is CONSUL and gFlake is enabled (GFlakeEnabled, which defaults to true).

Claims live in the Consul key/value store under the prefix genesis/cluster/<GFlakeNodeIdClusterName>/node-ids/. Each key under that prefix is a node ID. Its value is a JSON claim that records the identity that owns the ID (identity, which is ConsulNodeName or the hostname), a released flag, and timestamps (claimedAtEpochMs and lastSeenEpochMs). To list the claims, run:

consul kv get -recurse genesis/cluster/<name>/node-ids/

or call the HTTP API at /v1/kv/genesis/cluster/<name>/node-ids/?recurse. To find a host's node ID, look for the claim whose identity matches that host's identity; the ID is the last part of its key.

To return just one host's claim, filter the output on that host's identity. consul kv get -recurse prints each claim on its own line, as the key followed by its JSON value:

consul kv get -recurse genesis/cluster/<name>/node-ids/ | grep '<host identity>'

The node ID is the last part of the key at the start of the line that matches. Because grep matches the identity anywhere on the line, use the full identity, so that a shorter one does not also match another host's claim.

To check that a host's processes have registered, list the services in the Consul catalog, and the nodes behind one of them:

consul catalog services
consul catalog nodes -service=GENESIS_ROUTER

or call the HTTP API at /v1/catalog/services. Each Genesis process registers as a service named after the process, such as GENESIS_ROUTER, unless you set ConsulServiceNamePattern.

To tie a catalog entry back to its node-ID claim, look at its ServiceMeta. Each process's entry carries a genesisNodeIdentity key, and its value matches the identity field of the host's claim. To see it, call the HTTP API for one service:

curl http://localhost:8500/v1/catalog/service/GENESIS_ROUTER

The ServiceMeta field of each entry in the response contains the key:

"ServiceMeta": {
"genesisNodeIdentity": "<host identity>"
}
important

A host's claim is owned by its identity: ConsulNodeName if it is set, otherwise the hostname. In containers, set ConsulNodeName to a value that stays the same across restarts, such as a StatefulSet ordinal. If the identity changes on every restart, each restart claims a new ID, and eventually there are none left.

Apps that share a database must also share the same GFlakeNodeIdClusterName. Otherwise they claim IDs separately and can give the same node ID to two hosts writing to that database.

Fixing a node ID​

To give a host a fixed node ID, for example to keep the ID of an existing node, set the GENESIS_SYSDEF_NodeId environment variable or the -DNodeId JVM property on that host. Alternatively, set NodeId in the system definition together with GFlakeNodeIdExplicit=true.

A fixed ID is still claimed in Consul, so a process refuses to start if another host already holds that ID. A fixed ID applies to the whole host: a process refuses to start if you set one for it alone with GENESIS_SYSDEF_<PROCESS>_NodeId.

When a process can't get a node ID​

If a process can't claim a unique node ID, it refuses to start. This happens, for example, when every ID is taken, or when Consul stays unreachable after a few retries. The claim is made before logging is set up, so on a non-container install, look for the reason in <PROCESS>.log.err. In a container, the reason is in docker logs <container>: <PROCESS>.log.err is only written when processes are not started with --verbose, and the stock container starts them with --verbose.

Heartbeat and grace period​

While it runs, each process checks its host's claim in Consul and refreshes it. The check runs every quarter of GFlakeNodeIdGraceMinutes, which is every 7.5 minutes with the default of 30.

A process stops itself if it can no longer confirm that the ID is its own:

  • at once, if the claim is gone, has been released, can't be read, or now belongs to another host;
  • after about three quarters of GFlakeNodeIdGraceMinutes (about 22 minutes by default) if Consul stays unreachable. A brief Consul outage does nothing.

Another host can take an ID only once its owner has left the Consul catalog and the claim has gone unrefreshed for the whole grace period. A process that loses contact with Consul therefore stops before its ID can be handed to anyone else.

A shorter grace period frees the IDs of removed hosts sooner, but it also means a shorter Consul outage stops every process in the cluster.

Exit code 3​

A process that stops because it can no longer confirm its node ID exits with code 3, so you can tell it apart from an unrelated crash. Before it exits, the process logs an error that starts with Halting process:.

warning

Run Consul mode under a supervisor that restarts stopped processes. When it restarts, a process claims a node ID again, but the platform doesn't always restart it for you:

  • In Kubernetes, a restartPolicy restarts the container on any non-zero exit code.
  • Otherwise, the platform restarts a process only if scheduleRestart is set to true for it, and it gives up after three attempts.

Without one of these, a long Consul outage stops every process on every host, and they stay down until you run startServer again.

While ConsulSessionLockDelaySeconds is above 0, the other three settings are capped so that a process stops before the lock delay ends. A value outside its limits is adjusted when the process starts, and the process logs an error that gives the value it used.

Troubleshooting​

Request fails with 5xx when trying to reach a process that no longer exists​

Scenario: This might happen when a resource is moved from one process to another. For example, a requestReply originally served from REQ_REP_SERVICE_A is now moved to REQ_REP_SERVICE_B, but consul still holds a reference that is being served by the former.

Solution: Check the consul console (or cli) to see if there is still a resourceMap (under KeyValues) for the process that no longer exists. If there is, delete it. Then restart the Genesis services.