How To Automatically Change Port If Default Is In Use With Guard And Rails

Posted by Weston Ganger on March 01, 2016

I like Guard-Rails, how it just keeps working while I keep working. I dont like it if I tell it to start and it hangs up because I have another Rails app running too.

Here is how to set your Guardfile to automatically use a different port if its in use.

# Use port 3001 if 3000 is in use (this allows up to 2 instances)
guard :rails, port: (system("lsof -i:3000") ? 3001 : 3000) do

# OR

# For unlimited guard instances
port = 3000
port += 1 while system("lsof -i:#{port}")

guard :rails, port: port, host: '' do

So now if I already have a server running on port 3000 it will automatically switch to port 3001 and so on. Beauty!

Related External Links:

Posted in Rails and Tagged with guard rails 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts