Setting the Tomcat Http Port in Gradle

It's a simple matter to change Tomcat's port in your Spring App by adding it to the applications.properties file with

server.port: 8086

If you're going back and forth between WAR deployments and bootRuns as I sometimes do, you might want more flexibility.

Enter Gradle

We can add the system property in our Gradle bootRun task, so when we create a WAR or some other package we'll use the default port.

bootRun {
addResources = false
systemProperty 'server.port', '8086'
main = 'com.nixmash.springdata.mvc.WebInitializer'
}

We can also create a Gradle task to add the system property to bootRun. You can name the task anything you want, of course. I'm being extra uncreative today. With this approach we have flexibility in how our bootRun Tomcat port is assigned.

task 8086 << {
bootRun.systemProperty 'server.port', '8086'
}

bootRun {
addResources = false
main = 'com.nixmash.springdata.mvc.WebInitializer'
}

Execute both tasks with

$ gradle 8086 bootRun

Simply executing bootRun will launch the app at the default 8080. Otherwise we're 8086-ing it!

For completeness, if using a local Tomcat Server Deployment in IntelliJ we can add the port as a VM property in the server configuration. That syntax would be

-Dserver.port=8086

in the “VM Options” field.

Posted July 22, 2015 09:40 AM EDT

More Like This Post