3

I searched the internet for a "Hello, World" type program for Webrick in Ruby, but could not find anything that worked. I found this guide on SO but for the life of me could not get it to work.

Consulting the Ruby Documentation for Webrick led me to some code snippets that got me going in the right direction. There were no easy-to-follow tutorials so I wanted to add my answer on SO.

I was using Ubuntu 14.04 without Apache or Nginx and wanted my server for a virtual host. Webrick by default does not respond to requests concurrently but for me this was a plus in addition to its small footprint. I was hoping to get it working without the Rails framework for an even lighter footprint.

Community
  • 1
  • 1
pmagunia
  • 1,718
  • 1
  • 22
  • 33

1 Answers1

5

To get started, I installed Ruby with the Ubuntu package manager. If you are using CentOS or another Linux distribution, you can adapt this step to your particular package manager. Also make sure port 80 is open on your web server. It's possible to get SSL with Webrick but I chose not to at this point.

sudo apt-get install ruby

Here is the script which I named myapp.rb that I am using. I placed it /var/www/myapp. Ideally, I think it should not be in document root. You should also create a special user and group just to run the script to improve security (I have not outlined those steps here)

require 'webrick'

server = WEBrick::HTTPServer.new(:Port => 80,
                             :SSLEnable => false,
                             :DocumentRoot => '/var/www/myapp',
                             :ServerAlias => 'myapp.example.com')

server.mount_proc '/' do |req, res|
  res.body = 'Hello, world!'
end

trap 'INT' do server.shutdown end

server.start

The require statement above tells Ruby to include the Webrick classes when running the program. The second line of the script creates an instance of Webrick with the following options:

  • Use Port 80
  • Disable SSL
  • Set the document root to /var/www/myapp
  • Set the Server Alias to myapp.example.com

Of course, you'll have to configure your particular domains DNS'. The server.mount_proc is telling Ruby to serve the response, "Hello, world" at document root. I think you can specify a subdirectory there if you life. The Ruby Webrick documentation above has information on that.

The line that begins with trap means that the web server can be stopped with Ctrl-C. To start the script I typed the following at the SSH command line:

ruby myapp.rb
pmagunia
  • 1,718
  • 1
  • 22
  • 33