Dmytro Chyzhykov's Blog

Yet another programmer.

Running Embedded Jetty on a Random Available Port

Running Embedded Jetty on a random available port would be handful:

  • for integration testing: you can run several builds on the same continuous integration worker without port conflicts
  • for deployment: when you do not know where a particular port is taken or not
  • for development: you can run several instances of your web application just from your favourite IDE or CLI
  • for lulz

How to do this within code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.eclipse.jetty.server.Server;

public class EmbeddedJettyRandomAvailabalePortExample {

    public static void main(String...args) throws Exception {
        Server server = new Server(0);
        server.start();

        int port = server.getConnectors()[0].getLocalPort();

        System.out.println("Embedded Jetty has successfully started on port " + port);

        server.join();
    }

}

How would the output look like

1
2
3
INFO  2013-10-07 22:12:25,999 [org.eclipse.jetty.server.Server]:272 - jetty-8.1.13.v20130916
INFO  2013-10-07 22:12:26,080 [org.eclipse.jetty.server.AbstractConnector]:338 - Started SelectChannelConnector@0.0.0.0:59794
Embedded Jetty has successfully started on port 59794

Which version of library to use

In this example the 8.1.13.v20130916 version is used.

1
2
3
4
5
<dependency>
    <groupId>org.eclipse.jetty.aggregate</groupId>
    <artifactId>jetty-all-server</artifactId>
    <version>8.1.13.v20130916</version>
</dependency>

If you doubt which version of Jetty to use, follow the What Version Do I Use? page.