Embedded tomcat java application is running, but server cannot be reached
Asked Answered
T

2

14

I am trying to set up a basic embedded Tomcat server and am unable to get the Tomcat server to run.

public class Main {

    public static void main(String[] args) throws LifecycleException {

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8888);

        tomcat.start();
        tomcat.getServer().await();
    }
}

Running this java app in Eclipse provides the output:

June 19, 2019 12:00:00 PM org.apache.catalina.core.StandardService startInternal

INFO: Starting service [Tomcat]

And then waits until I hit stop, as expected, but when I run curl localhost:8888 in the terminal, i get curl: (7) Failed connect to localhost:8888; Connection refused.

I've followed this tutorial exactly, but I cannot seem to get the server to actually run. Also, netstat -nlt does not show the port 8888 being open.

My build.gradle has a single dependency:

implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.21'

Is there something I'm missing here?

Tyra answered 19/6, 2019 at 13:31 Comment(1)
Have the same issue, followed the same article alsoMargheritamargi
M
18

I just found solution I use tomcat 9, and it looks like we need to call method getConnector() on tomcat object.

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.getConnector();
Margheritamargi answered 11/12, 2019 at 9:22 Comment(0)
L
11

Tomcat 9 no longer adds a Connector by default like previous versions. You can do the following to add one:

final Connector connector = new Connector();
connector.setPort(port);
tomcat.getService().addConnector(connector);

As mentioned in another answer, you can also call tomcat.getConnector(); which is a side-affecting getter.

Lactometer answered 23/4, 2020 at 18:54 Comment(1)
For background/reference, this change was introduced in Tomcat 9.0.0 Milestone 14: Stop creating a default connector on start in embedded mode. When you use new Connector(), you get a HTTP/1.1 NIO connector by default.Unitarianism

© 2022 - 2024 — McMap. All rights reserved.