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

Posted By Weston Ganger

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
  #watches
end

# OR

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

guard :rails, port: port, host: '0.0.0.0' do
  #watches
end

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:

Article Topic:Software Development - Ruby / Rails

Date:March 01, 2016