RailFan
RailFan

Reputation: 261

How to find the local port a rails instance is running on?

So I would like my Rails app instances to register themselves on a "I'm up" kind of thing I'm playing with, and I'd like it to be able to mention what local port it's running on. I can't seem to find how to do it - in fact just finding out its IP is tricky and needs a bit of a hack.

But no problem, I have the IP - but how can I find what port my mongrel/thin/webrick server is running on?

To be super explicit, if I start a rails app using script/server -p 3001, what can I do to pull that 3001 inside the app.

Upvotes: 24

Views: 18439

Answers (7)

Hartator
Hartator

Reputation: 5145

For Puma servers, you have to use this:

Puma::Server.current.connected_port
=> 3001

Upvotes: 0

David Hempy
David Hempy

Reputation: 6237

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.

Upvotes: 6

jfly
jfly

Reputation: 303

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]

Upvotes: 9

hiroshi
hiroshi

Reputation: 7251

For Rails 5.1 development server.

if Rack::Server.new.options[:Port] != 9292 # rals s -p PORT
  local_port = Rack::Server.new.options[:Port]
else
  local_port = (ENV['PORT'] || '3000').to_i # ENV['PORT'] for foreman
end

Upvotes: 6

superluminary
superluminary

Reputation: 49162

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]

Upvotes: 11

ndbroadbent
ndbroadbent

Reputation: 13793

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.

Upvotes: 21

Lars Haugseth
Lars Haugseth

Reputation: 14881

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

Upvotes: 15

Related Questions