0

I'm looking to set the listening port within my Rack and Sinatra app, using the PORT environment variable if set otherwise to a default.

I thought I may be able to do something like the following but I'm unsure if this is even the right approach.

class ApplicationController < Sinatra::Base
  set :port, ENV['PORT'] || 3000

  get '/' do
    'Hello, World!'
  end
end

This doesn't seem to work, at least not with the rackup command. What's the correct way to do this?

Zak
  • 1,910
  • 3
  • 16
  • 31
  • Do you mean [how do I set and use global variables in Sinatra](https://stackoverflow.com/questions/4525482/in-sinatraruby-how-should-i-create-global-variables-which-are-assigned-values)? – tadman Apr 04 '19 at 22:28
  • @tadman I don't, I'm asking how to set the port using an environment variable... – Zak Apr 04 '19 at 22:33
  • 1
    What about this isn't working? `PORT=9090 rackup` – tadman Apr 04 '19 at 22:41
  • @tadman Well it runs on port 9292 when I do that! – Zak Apr 04 '19 at 22:42
  • so, there are no issues here? – max pleaner Apr 05 '19 at 02:48
  • @maxpleaner Uhm...well that's the wrong port... – Zak Apr 05 '19 at 10:25
  • My experience with Sinatra is that it seems to ignores the port configuration variable set inside the application controller class as far as what `rackup` sees. Even if you wrote, `set :port, 8080` directly, it would still be 9292, so it's not an environment variable reading issue. I ended up always just writing the port I want on the `rackup` command line, as the posted answer indicated. I was not aware of the `config.ru` comment method, which the answer also shows. I may change over to that. – lurker May 25 '19 at 14:30

1 Answers1

4

rackup takes -p PORT argument.

You can do:

rackup -p $PORT

In config.ru you can also define the options in a comment on the first line:

#\ -p 9090

I'm not sure if that can handle $PORT.

If you look at the source code for rackup, it's very simple:

#!/usr/bin/env ruby
# frozen_string_literal: true

require "rack"
Rack::Server.start

That's the whole file.

Rack::Server.start accepts an options hash as parameter and one of the options is :Port.

You could make your own start.sh that says:

#!/usr/bin/env ruby
# frozen_string_literal: true

require "rack"
Rack::Server.start(Port: ENV['PORT'] || 3000)
Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
  • 1
    Thanks for the answer – I didn't know about starting Rack programatically, I think I'll use that! – Zak Apr 05 '19 at 10:27