=head1 NAME

Dancer::Deployment - common ways to put your Dancer app into use

=head1 DESCRIPTION

Dancer has been designed to be flexible, and this flexibility extends to your
choices when deploying your Dancer app.


=head2 Running as a cgi-script

In providing ultimate flexibility in terms of deployment, your Dancer app can
be run as a simple cgi-script out-of-the-box. No additional web-server
configuration needed.  Your web server should recognize .cgi files and be able
to serve Perl scripts.  The Perl module Plack::Runner is required.

Start by adding the following to your apache configuration:

    <VirtualHost *:80>
        ServerName your.server.domain

        # The DocumentRoot should point to your "public" directory
        DocumentRoot "/path/to/dancer/public"

        <Directory "/path/to/dancer/public">
            AllowOverride None

            # +Indexes is important, if you don't enable it, Apache will silently try to get /index.html
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch +Indexes
            
			Order allow,deny
            Allow from all
            AddHandler cgi-script .cgi
        </Directory>

    </VirtualHost>

Enable Pretty-URLs if your web server supports .htaccess files and mod_rewrite.
Place this code in a file called .htaccess (or directly in your VirtualHost
configuration) in your application's root folder:

    # BEGIN dancer application htaccess
    DirectoryIndex dispatch.cgi/
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteRule (.*) /dispatch.cgi/$1 [L]
    # END dancer application htaccess

Now you can access your dancer application URLs as if you were using the
embedded web server.

    http://localhost/

This option is a no-brainer, easy to setup, low maintenance but serves requests
slower than all other options.

=head2 Running stand-alone

At the simplest, your Dancer app can run standalone, operating as its own
webserver using HTTP::Simple::PSGI.

Simply fire up your app:

    $ perl ./mysuperwebapp.pl
    >> Listening on 0.0.0.0:3000
    == Entering the dance floor ...

Point your browser at it, and away you go!

This option can be useful for small personal web apps or internal apps, but if
you want to make your app available to the world, it probably won't suit you.

=head3 Running on Perl webservers with plackup

A number of Perl web servers supporting PSGI are available on cpan:

=over 4

=item Starman

C<Starman> is a high performance web server, with support for preforking, signals, ...

=item Twiggy

C<Twiggy> is an C<AnyEvent> web server, it's light and fast.

=item Corona

C<Corona> is a C<Coro> based web server.

=back

To start your application, just run plackup

   $ plackup -s Twiggy -p 5000 <YOURAPP>.pl

As you can see, the scaffolded Perl script for your app can be used as a PSGI
startup file.


=head3 Running multiple apps with Plack::Builder

You can use Plack::Builder to mount multiple Dancer applications on
a L<PSGI> webserver like L<Starman>.

Start by creating a simple app.psgi file:

    use Dancer;
    use Plack::Builder;
    load_app 'MyApp1', 'MyApp2';

    use Dancer::Config 'setting';
    setting apphandler => 'PSGI';
    Dancer::Config->load;

    my $app1 = sub {
        my $env = shift;
        my $request = Dancer::Request->new( $env );
        Dancer->dance( $request );
    };
    my $app2 = sub {
        my $env = shift;
        my $request = Dancer::Request->new( $env );
        Dancer->dance( $request );
    };

    builder {
        mount "/app1" => builder {$app1};
        mount "/app2" => builder {$app2};
    };

and now use L<Starman>

    plackup -a app.psgi -s Starman


=head3 Using daemontools to create a service

daemontools is a collection of tools for managing UNIX services. You can use it to easily start/restart/stop services.

A basic script to start an application: (in /service/application/run)

    #!/bin/sh

    # if your application is not installed in @INC path:
    export PERL5LIB='/path/to/your/application/lib'

    exec 2>&1 \
    /usr/local/bin/plackup -s Starman -a /path/to/your/application/app.pl -p 5000



=head3 Running stand-alone behind a proxy / load balancer

Another option would be to run your app stand-alone as described above, but then
use a proxy or load balancer to accept incoming requests (on the standard port
80, say) and feed them to your Dancer app.

This could be achieved using various software; examples would include:

=head4 Using Apache's mod_proxy

You could set up a VirtualHost for your web app, and proxy all requests through
to it:

    <VirtualHost mywebapp.example.com:80>
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/
    </VirtualHost>

Or, if you want your webapp to share an existing VirtualHost, you could have it
under a specified dir:

    ProxyPass /mywebapp/ http://localhost:3000/
    ProxyPassReverse /mywebapp/ http://localhost:3000/


=head4 Using perlbal

C<perlbal> is a single-threaded event-based server written in Perl supporting HTTP load
balancing, web serving, and a mix of the two, available from
L<http://www.danga.com/perlbal/>

It processes hundreds of millions of requests a day just for LiveJournal, Vox
and TypePad and dozens of other "Web 2.0" applications.

It can also provide a management interface to let you see various information on
requests handled etc.

It could easily be used to handle requests for your Dancer apps, too.

It can be easily installed from CPAN:

    perl -MCPAN -e 'install Perlbal'

Once installed, you'll need to write a configuration file.  See the examples
provided with perlbal, but you'll probably want something like:

    CREATE POOL my_dancers
    POOL my_dancers ADD 10.0.0.10:3030
    POOL my_dancers ADD 10.0.0.11:3030
    POOL my_dancers ADD 10.0.0.12:3030
    POOL my_dancers ADD 10.0.0.13:3030

    CREATE SERVICE my_webapp
    SET listen          = 0.0.0.0:80
    SET role            = reverse_proxy
    SET pool            = my_dancers
    SET persist_client  = on
    SET persist_backend = on
    SET verify_backend  = on
    ENABLE balancer




=head4 Using balance

C<balance> is a simple load-balancer from Inlab Software, available from
L<http://www.inlab.de/balance.html>.

It could be used simply to hand requests to a standalone Dancer app. You could
even run several instances of your Dancer app, on the same machine or on several
machines, and use a machine running balance to distribute the requests between
them, for some serious heavy traffic handling!

To listen on port 80, and send requests to a Dancer app on port 3000:

    balance http localhost:3000

To listen on a specified IP only on port 80, and distribute requests between
multiple Dancer apps on multiple other machines:

    balance -b 10.0.0.1 80 10.0.0.2:3000 10.0.0.3:3000 10.0.0.4:3000


=head4 Using Lighttpd

You can use Lighttp's mod_proxy:

    $HTTP["url"] =~ "/application" {
        proxy.server = (
            "/" => (
                "application" => ( "host" => "127.0.0.1", "port" => 3000 )
            )
        )
    }

This configuration will proxy all request to the B</application> path to the path B</> on localhost:3000.

=head4 Using Nginx

with Nginx:

    upstream backend {
        server 10.0.0.1:8080;
        server 10.0.0.2:8080;
        ...
    }

    server {
        location / {
            proxy_pass http://backend;
        }
    }

=head2 Running from Apache

You can run your Dancer app from Apache using the following examples:


=head3 Running from Apache with Plack

You can run your app from Apache using PSGI (Plack), with a config like the
following:

    <VirtualHost myapp.example.com>
        ServerName www.myapp.example.com
        ServerAlias myapp.example.com
        DocumentRoot /websites/myapp.example.com

        <Directory /home/myapp/myapp>
            AllowOverride None
            Order allow,deny
            Allow from all
        </Directory>

        <Location />
            SetHandler perl-script
            PerlHandler Plack::Handler::Apache2
            PerlSetVar psgi_app /websites/myapp.example.com/app.pl
        </Location>

        ErrorLog  /websites/myapp.example.com/logs/error_log
        CustomLog /websites/myapp.example.com/logs/access_log common
    </VirtualHost>

To set the environment you want to use for your application (production or development), you can set it this way:

    <VirtualHost>
        ...
        SetEnv DANCER_ENVIRONMENT "production"
        ...
    </VirtualHost>

=head3 Running from Apache via FastCGI

You can run your Dancer app from Apache via FastCGI using the dispatch.fcgi
script written by the dancer helper script when you create your application
scaffolding:

    <VirtualHost *:80>
        ServerName localhost
        DocumentRoot "/tmp/TestApp/public"

        <Directory "/tmp/TestApp/public">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
            AddHandler fastcgi-script .fcgi
        </Directory>

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ /dispatch.fcgi [QSA,L]
    </VirtualHost>


=head3 Running from Apache under appdir

If you want to deploy multiple applications under the same VirtualHost, using
one application per directory for example, you can do the following.

This example uses the FastCGI dispatcher that comes with Dancer, but you should
be able to adapt this to use any other way of deployment described in this
guide. The only purpose of this example is to show how to deploy multiple
applications under the same base directory/virtualhost.

    <VirtualHost *:80>
        ServerName localhost
        DocumentRoot "/path/to/rootdir"
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f

        <Directory "/path/to/rootdir">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
            AddHandler fastcgi-script .fcgi
        </Directory>

        RewriteRule /App1(.*)$ /App1/public/dispatch.fcgi$1 [QSA,L]
        RewriteRule /App2(.*)$ /App2/public/dispatch.fcgi$1 [QSA,L]
        ...
        RewriteRule /AppN(.*)$ /AppN/public/dispatch.fcgi$1 [QSA,L]
    </VirtualHost>

Of course, if your Apache configuration allows that, you can put the
RewriteRules in a .htaccess file directly within the application's directory,
which lets you add a new application without changing the Apache configuration.


=head2 Running on lighttpd

It is very easy to configure lighttpd to deploy Dancer applications. Multiple
applications can be deployed on the same server by setting up virtual hosts.
You can configure name based virtual hosts with conditional blocks that start
with:

    $HTTP["host"] == "myapp.example.com" { ...

Or you can configure port based virtual hosts:

    $SERVER["socket"] == ":5000" { ...

There is no need to explicitly set the document root for the following examples.
It will be set to the public folder implicitly, since that is where the dispatch
scripts live. If you would like your document root to be elsewhere, you can add
this line inside of the conditional block:

    server.document-root = "/somewhere/else/"


=head3 Running on lighttpd (CGI)

Make sure mod_cgi is enabled. This example uses a name based virtual host.

    cgi.assign = ( ".cgi" => "" )
    $HTTP["host"] == "myapp.example.com" {
        alias.url += ("" => "/path/to/myapp/public/dispatch.cgi")
    }


=head3 Running on lighttpd (FastCGI)

Make sure mod_fcgi is enabled. You also must install the FCGI module from
CPAN.

=head4 Script

This example uses a script based virtual host.

Your lighttpd configuration:

    $HTTP["url"] == "^/app" {
        fastcgi.server += (
            ".fcgi" => ((
                "bin-path" => "/path/to/myapp/public/dispatch.fcgi",
                "socket" => "/tmp/fcgi.sock",
            ))
        )
        alias.url += ("" => "/path/to/myapp/public/dispatch.fcgi")
    }

=head4 TCP/IP

This example uses TCP/IP.

Your lighttpd configuration:

    $HTTP["url"] == "^/app" {
        fastcgi.server += (
            "/app" => (
                "" => (
                    "host" => "127.0.0.1",
                    "port" => "5000",
                    "check-local" => "disable",
                )
           )
       )
   }

Launch your application

    plackup -s FCGI --port 8080 app.pl

=head4 Unix socket

This example uses a socket.

Your lighttpd configuration:

    $HTTP["url"] =~ "^/app" {
        fastcgi.server += (
            "/app" => (
                "" => (
                    "socket" => "/tmp/fcgi.sock",
                    "check-local" => "disable",
                )
            )
        )
    }

Launch your application:

    plackup -s FCGI --listen /tmp/fcgi.sock app.pl
