Change Dropwizard default ports

From the command line, you can set them this way, in Dropwizard 0.6:

java -Ddw.http.port=9090 -Ddw.http.adminPort=9091 -jar yourapp.jar server yourconfig.yml

If you use Dropwizard 0.7, the system properties are set this way:

java -Ddw.server.applicationConnectors[0].port=9090 -Ddw.server.adminConnectors[0].port=9091 -jar yourapp.jar server yourconfig.yml

I seems that, if you configure ports through system properties, you also need to set them in the yml (the system property takes precedence, anyway). At least that's happening to me in Dropwizard 0.7. Example of the YAML port configuration:

server:
  applicationConnectors:
  - type: http
    port: 8090
  adminConnectors:
  - type: http
    port: 8091

If you don't put those ports in the YAML, Dropwizard complains:

Exception in thread "main" java.lang.IllegalArgumentException: Unable to override server.applicationConnectors[0].port; node with index not found.

You can update the ports in your yaml configuration file:

http:
  port: 9000
  adminPort: 9001

See http://www.dropwizard.io/0.9.2/docs/manual/configuration.html#http for more information.

EDIT

If you've migrated to Dropwizard 0.7.x, 0.8.x, 0.9.x you can use the following:

server:
  applicationConnectors:
  - type: http 
    port: 9000
  adminConnectors:
  - type: http
    port: 9001

This is what I've done for my test applications (0.7.x, 0.8.x, 0.9.x):

public class TestConfiguration extends Configuration {

  public TestConfiguration() {
    super();
    // The following is to make sure it runs with a random port. parallel tests clash otherwise
    ((HttpConnectorFactory) ((DefaultServerFactory) getServerFactory()).getApplicationConnectors().get(0)).setPort(0);
    // this is for admin port
    ((HttpConnectorFactory) ((DefaultServerFactory) getServerFactory()).getAdminConnectors().get(0)).setPort(0);   } }

0 gives a random port that is available.

I know it's not pretty but couldn't find a better way to do it programmatically. I needed to make sure ports don't clash between different integration tests, because they run in parallel. Creating a yml file randomly for each test would have been uglier I believe.

Oh and this is how you get the running port later on:

@Override
  public void run(TestConfiguration configuration, Environment environment) throws Exception {
    this.environment = environment;
    // do other stuff if you need to
  }

  public int getPort() {
    return ((AbstractNetworkConnector) environment.getApplicationContext().getServer().getConnectors()[0]).getLocalPort();
  }