Fork me on GitHub

The WebDevil

Enjoy development

Сделал небольшую пачку оберток на сервере для управления приложениями.

Для начала воспользовался кластером mongrel:

gem install mongrel_cluster

и создал юзеря, от которого все монгрели будут выполняться:

adduser --system --no-create-home --shell /bin/false --group mongrel

Правда, мне понадобилось сделать vipw и vigr, чтобы подправить ID пользователя и группы – чтоб они совпадали.

Теперь, в папке с приложением сделал

mongrel_rails cluster::configure -e production -p 3000 -N 5 -c ./ -a 127.0.0.1 --user mongrel --group mongrel

и получил в результате в config/mongrel_cluster.yml конфиг для кластера монгрелей. Вот такого вида:

---
user: mongrel
cwd: /var/www/lighttpd/www.example.com
log_file: log/mongrel.log
port: "8000"
environment: production
group: mongrel
address: 127.0.0.1
pid_file: tmp/pids/mongrel.pid
servers: 5

Запускается оно через mongrel_rails cluster::start.
Но надо же что-то сделать, чтоб оно загружалось при старте системы. И вот что я нашел и сделал.

mkdir /etc/mongrel_cluster/
mkdir /etc/mongrel_cluster/available
mkdir /etc/mongrel_cluster/enabled
mv /var/www/lighttpd/www.example.com/config/mongrel_cluster.yml /etc/mongrel_cluster/available/www.example.com.yml
ln -s /etc/mongrel_cluster/available/www.example.com.yml /etc/mongrel_cluster/enabled/www.example.com.yml

Теперь создадим скрипт /etc/init.d/mongrel_cluster:

#!/bin/bash

set -e

mongrel_cluster_ctl -v -c /etc/mongrel_cluster/enabled $@

и выполняем

chmod +x /etc/init.d/mongrel_cluster
update-rc.d -f mongrel_cluster defaults

Также для удобства запуска-остановки отдельного приложения я сделал мелкий скрипт /etc/mongrel_cluster/operation.sh:

#!/bin/bash

set -e

CONFIGS=/etc/mongrel_cluster/enabled

mongrel_rails cluster::$1 -C $CONFIGS/$2.yml

Поьзоваться им можно так: /etc/mongrel_cluster/operation.sh start www.example.com
Собственно, на этом с монгрелем все.
Далее – lighttpd. Почему не nginx? Я не нашел никаких доводов за или против. В конце-концов, оба они работают как reverse-proxy к монгрелю, и несложно сменить демон – никаких переработок приложения не потребуется.

Итак, вот конфиг lighttpd:

server.modules                  = ( "mod_access", "mod_accesslog", "mod_compress", "mod_rewrite", "mod_proxy", "mod_redirect" )
server.document-root            = "/var/www/lighttpd/default/"
server.errorlog                 = "/var/log/lighttpd/error.log"
server.port                     = 80
server.bind                     = "77.120.99.179"
server.pid-file                 = "/var/run/lighttpd.pid"
server.username                 = "www-data"
server.groupname                = "www-data"
server.tag                      = "lighttpd"

index-file.names                = ( "index.php", "index.html", "index.htm" )
url.access-deny                 = ( "~", ".inc" )
static-file.exclude-extensions  = ( ".php", ".pl", ".fcgi" )

accesslog.filename              = "/var/log/lighttpd/access.log"

compress.cache-dir              = "/var/cache/lighttpd/compress/"
compress.filetype               = ("text/plain", "text/html", "application/x-javascript", "text/css", "text/xml" )

include_shell                   "/usr/share/lighttpd/create-mime.assign.pl"
include_shell                   "/usr/share/lighttpd/include-conf-enabled.pl"

var.basedir = "/var/www/lighttpd/"

#### SITES ####
$HTTP["host"] == "example.com" {
    url.redirect = ("^/(.*)$" => "http://www.example.com/$1")
}
$HTTP["host"] == "www.example.com" {
    server.name = "www.example.com"
    server.document-root = basedir + server.name + "/public"
    accesslog.filename = basedir + server.name + "/log/access.log"
   
    $HTTP["url"] !~ "^/(stylesheets|javascripts|images|files)/" {
        proxy.balance = "fair"
        proxy.server  = (
            "/" => (
                ( "host" => "127.0.0.1", "port" => 8000 ),
                ( "host" => "127.0.0.1", "port" => 8001 ),
                ( "host" => "127.0.0.1", "port" => 8002 ),
                ( "host" => "127.0.0.1", "port" => 8003 ),
                ( "host" => "127.0.0.1", "port" => 8004 )
            )
        )
    }
}

Я обеспечил прямой доступ к статике посредством lighttpd, не заворачивая статику через mongrel (везде я встречал заворачивание всего на монгрели, что, ИМХО, не есть хорошо).
Весьма настоятельно рекомендую в приложении создать файлик log/access.log и обеспечить в него запись пользователю www-data, от которого работает lighttpd.

Собственно, все. Ругайте.

UPD: в процессе работы проявились особенности Safari & IE. Для них надо в конфиге lighttpd добавить

$HTTP["useragent"] =~ "^(.*MSIE.*)|(.*AppleWebKit.*)$" {
    server.max-keep-alive-requests = 0
}

One Response to “lighttpd and rails”

  1. уж больно расхлебаный скрипт для модгрела:
    вот мой:

    #!/bin/bash
    CONF_DIR=/etc/mongrel_cluster
    PID_DIR=/var/run/mongrel_cluster
    USER=wwwrun
    GROUP=www

    RETVAL=0

    # Gracefully exit if the controller is missing.
    which mongrel_cluster_ctl >/dev/null || exit 0

    # Go no further if config directory is missing.
    [ -d "$CONF_DIR" ] || exit 0

    case “$1″ in
    start)
    # Create pid directory
    mkdir -p $PID_DIR
    chown $USER:$GROUP $PID_DIR

    mongrel_cluster_ctl start -c $CONF_DIR
    RETVAL=$?
    ;;
    stop)
    mongrel_cluster_ctl stop -c $CONF_DIR
    RETVAL=$?
    ;;
    restart)
    mongrel_cluster_ctl restart -c $CONF_DIR
    RETVAL=$?
    ;;
    status)
    mongrel_cluster_ctl status -c $CONF_DIR
    RETVAL=$?
    ;;
    *)
    echo “Usage: mongrel_cluster {start|stop|restart|status}”
    exit 1
    ;;
    esac

    exit $RETVAL

    DeViL