How to find the local port a rails instance is running on?
You can call Rails::Server.new.options[:Port]
to get the port that your Rails server is running on. This will parse the -p 3001
args from your rails server
command, or default to port 3000
.
From inside any controller action, check the content of request.port, thus:
class SomeController < ApplicationController
def some_action
raise "I'm running on port #{request.port}."
end
end
Two ways.
If you're responding to a request in a controller or view, use the request object:
request.port
If you're in an initialiser and don't have access to the request object use the server options hash:
Rails::Server.new.options[:Port]
I played around with this a bit, and this might be the best solution for Rails 5.1:
Rails::Server::Options.new.parse!(ARGV)[:Port]
Building on the other answers (which saved my bacon!), I expanded this to give sane fallbacks:
In development:
port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 3000 rescue 3000
In all other env's:
port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 80 rescue 80
The rescue 80
covers you if you're running rails console
. Otherwise, it raises NameError: uninitialized constant Rails::Server
. (Maybe also early in initializers? I forget...)
The || 80
covers you if no -p option is given to server. Otherwise you get nil.