(system) To support configurations with multiple docker networks, bind to the "most local" interface.

This commit is contained in:
Viktor Lofgren 2024-12-19 20:18:57 +01:00
parent 64d32471dd
commit e1783891ab
3 changed files with 36 additions and 3 deletions

View File

@ -6,6 +6,9 @@ import nu.marginalia.service.ServiceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Objects;
import java.util.UUID;
@ -84,10 +87,37 @@ public class ServiceConfigurationModule extends AbstractModule {
private String getBindAddress() {
String configuredValue = System.getProperty("service.bind-address");
if (configuredValue != null) {
logger.info("Using configured bind address {}", configuredValue);
return configuredValue;
}
return "127.0.0.1";
try {
return Objects.requireNonNullElse(getLocalNetworkIP(), "0.0.0.0");
}
catch (Exception ex) {
logger.warn("Failed to get local network IP, falling back to bind to 0.0.0.0", ex);
return "0.0.0.0";
}
}
public static String getLocalNetworkIP() throws Exception {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
while (nets.hasMoreElements()) {
NetworkInterface netif = nets.nextElement();
if (!netif.isUp() || netif.isLoopback()) {
continue;
}
Enumeration<InetAddress> inetAddresses = netif.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress addr = inetAddresses.nextElement();
if (addr.isSiteLocalAddress() && !addr.isLoopbackAddress()) {
return addr.getHostAddress();
}
}
}
return null;
}
}

View File

@ -7,6 +7,8 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.net.InetSocketAddress;
public class MetricsServer {
@Inject
@ -15,7 +17,8 @@ public class MetricsServer {
if (configuration.metricsPort() < 0)
return;
Server server = new Server(configuration.metricsPort());
Server server = new Server(new InetSocketAddress(configuration.bindAddress(), configuration.metricsPort()));
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);

View File

@ -8,7 +8,7 @@ jib {
}
container {
mainClass = application.mainClass
jvmFlags = ['-Dservice.bind-address=0.0.0.0', '-Dservice.useDockerHostname=TRUE', '-Dsystem.homePath=/wmsa']
jvmFlags = ['-Dservice.useDockerHostname=TRUE', '-Dsystem.homePath=/wmsa']
volumes = ['/wmsa/conf', '/wmsa/model', '/wmsa/data', '/var/log/wmsa']
}
}