Senthil Kumaran
Senthil Kumaran

Reputation: 56841

Sinatra app is not starting the internal webserver

I have a very simple Sinatra app to test.

ubuntu@ip:~/helloworld$ cat app.rb
# app.rb
require 'sinatra'

class HelloWorldApp < Sinatra::Base
  get '/' do
    "Hello, world!"
  end
end
ubuntu@:~/helloworld$ cat config.ru
# config.ru
require './app'
run HelloWorldApp

When I start it on Ubuntu, it runs like this. It is not starting the listener. Or the webserver

$ rackup
[2016-03-18 22:23:58] INFO  WEBrick 1.3.1
[2016-03-18 22:23:58] INFO  ruby 2.2.3 (2015-08-18) [x86_64-linux]
[2016-03-18 22:23:58] INFO  WEBrick::HTTPServer#start: pid=18049 port=9292

Or this way

$ ruby app.rb
[2016-03-18 22:28:00] INFO  WEBrick 1.3.1
[2016-03-18 22:28:00] INFO  ruby 2.2.3 (2015-08-18) [x86_64-linux]
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from WEBrick
[2016-03-18 22:28:00] INFO  WEBrick::HTTPServer#start: pid=18087 port=4567

Where as on a Mac, when I start the an app, it runs like this.

$ ruby app.rb
== Sinatra (v1.4.7) has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.3.1 codename Triple Espresso)
>> Maximum connections set to 1024
>> Listening on localhost:4567, CTRL+C to stop

It is listening on Localhost. What's the problem with my Ubuntu that it is not able to start the internal webserver. Any troubleshooting instructions?

Upvotes: 1

Views: 1755

Answers (1)

matt
matt

Reputation: 79733

I think there are a couple of things going on here.

First, Thin versus Webrick. Rack and Sinatra will both try to find a suitable webserver to use when starting. They will look for Thin, but if it is not available they will both fall back to using Webrick. The solution is to install Thin on your Ubuntu server with gem install thin. You might want to look into using Bundler and adding the thin gem to it to ensure you always have the same gems in development and production.

Second, accessing the server from another machine. By default, when starting up in development mode both rackup and Sinatra’s built in server will only listen to localhost. To bind to 0.0.0.0 you will either need to specify the host explicitly (either with the -o option to rackup or with set :bind '0.0.0.0' for the Sinatra built in sever), or start in production mode using the RACK_ENV environment variable.

One additional thing – in your current setup running ruby app.rb won’t actually start your application. It will run the default Sinatra::Application (which in this case is empty) rather than your HelloWorldApp, since you are using the modular style. To get this to run as you expect you should change your require line to

require 'sinatra/base'

and add

HelloWorldApp.run! if app_file == $0

to the end of the file.

Upvotes: 4

Related Questions