Search code examples
rubysinatraportrack

Use PORT environment variable in Rack/Sinatra


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?


Solution

  • 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)