mongrel_cluster with Nonconsecutive Ports

Need to run mongrel_cluster with nonconsecutive ports? No problem.

WebFaction assigns ports to its users through the control panel. The panel will not assign you consecutive ports. You can still use ports that aren’t assigned to you, but I assume that WebFaction does not want you to. Running mongrel_cluster without stretching or breaking the rules requires some effort. Unmodified, mongrel_cluster will only spawn mongrel_rails listeners on consecutive ports. Configuration is limited to specifying the first port and the number of instances. The situation with WebFaction requires a more precise way to configure ports. We will need to modify the mongrel_cluster code. All we need to do is add one line.

The file requiring modification is lib/mongrel_cluster/init.rb inside the mongrel_cluster gem directory. The easiest way to find and open this file for editing is to execute the following command:

nano `locate lib/mongrel_cluster/init.rb`

Locate the read_options method. In version 1.0.5, it should read:

def read_options
    @options = {
        "environment" => ENV['RAILS_ENV'] || "development",
        "port" => 3000,
        "pid_file" => "tmp/pids/",
        "log_file" => "log/mongrel.log",
        "servers" => 2
    conf = YAML.load_file(@config_file)
    @options.merge! conf if conf

    process_pid_file @options["pid_file"]
    process_log_file @options["log_file"]

    start_port = end_port = @only
    start_port ||=  @options["port"].to_i
    end_port ||=  start_port + @options["servers"] - 1
    @ports = (start_port..end_port).to_a

Add the following line to the end of the method:

@ports = @options["ports"] if @options["ports"] && !@only

The addition recognizes a parameter named ‘ports’ in config/mongrel_cluster.yml. Unless a single port is specified on the command line using the --only option, ‘ports’ will be respected over the ‘port’ and ‘servers’ parameters used to specify a continuous range. The ‘ports’ parameter should be accompanied by an array of integers in YAML format. An example mongrel_cluster.yml file that defines nonconsecutive ports follows:

cwd: /home/user/webapps/railsapp
environment: production
user: user
group: user
log_file: log/mongrel.log
pid_file: tmp/pids/
- 3333
- 3335
- 3359
- 3401

The one line addition does not give you the ability to define discontinuous ports on the command line. You must edit mongrel_cluster.yml to do so.