sourCEntral - mobile manpages




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


version 0.160003


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

Running as a cgi-script (or fast-cgi) under Apache
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 (httpd.conf or sites−available/*site*):

    <VirtualHost *:80>
        # /srv/ is the root of your
        # dancer application
        DocumentRoot /srv/
        ServerAdmin you AT example DOT com
        <Directory "/srv/">
           AllowOverride None
           Options +ExecCGI −MultiViews +SymLinksIfOwnerMatch
           Order allow,deny
           Allow from all
           AddHandler cgi−script .cgi
         RewriteEngine On
         RewriteCond %{REQUEST_FILENAME} !−f
         RewriteRule ^(.*)$ /dispatch.cgi$1 [QSA,L]
         ErrorLog  /var/log/apache2/−error.log
         CustomLog /var/log/apache2/−access_log common

Note that when using fast-cgi your rewrite rule should be:

        RewriteRule ^(.*)$ /dispatch.fcgi$1 [QSA,L]

Here, the mod_rewrite magic for Pretty-URLs is directly put in Apache’s configuration. But if your web server supports ".htaccess" files, you can drop those lines in a ".htaccess" file.

To check if your server supports mod_rewrite type "apache2 −l" to list modules. To enable "mod_rewrite" on Debian or Ubuntu, run "a2enmod rewrite". Place following code in a file called ".htaccess" in your application’s root folder:

    # BEGIN dancer application htaccess
    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.


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

You can use the same technique to deploy with FastCGI, by just changing the lines:

        AddHandler cgi−script .cgi


        AddHandler fastcgi−script .fcgi

Auto Reloading with Plack and Shotgun
To edit your files without the need to restart the webserver on each file change, simply start your Dancer2 app using plackup and Plack::Loader::Shotgun:

    $ plackup −L Shotgun bin/app.psgi
    HTTP::Server::PSGI: Accepting connections at http://0:5000/

Point your browser at it. Files can now be changed in your favorite editor and the browser needs to be refreshed to see the saved changes.

Please note that this is not recommended for production for performance reasons. This is the Dancer2 replacement solution of the old Dancer experimental "auto_reload" option.

On Windows, Shotgun loader is known to cause huge memory leaks in a fork-emulation layer. If you are aware of this and still want to run the loader, please use the following command:

    > set PLACK_SHOTGUN_MEMORY_LEAK=1 && plackup −L Shotgun bin\app.psgi
    HTTP::Server::PSGI: Accepting connections at http://0:5000/

Running stand-alone
At the simplest, your Dancer app can run standalone, operating as its own webserver using HTTP::Server::PSGI.

Simply fire up your app:

    $ perl bin/app.psgi
    >> Listening on
    == 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.

Running on Perl webservers with plackup

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

"Starman" is a high performance web server, with support for preforking, signals, multiple interfaces, graceful restarts and dynamic worker pool configuration.

Twiggy <>

"Twiggy" is an "AnyEvent" web server, it’s light and fast.

Corona <>

"Corona" is a "Coro" based web server.

To start your application, just run plackup (see Plack and specific servers above for all available options):

   $ plackup bin/app.psgi
   $ plackup −E deployment −s Starman −−workers=10 −p 5001 −a bin/app.psgi

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

Enabling content compression

Content compression (gzip, deflate) can be easily enabled via a Plack middleware (see "Plack::Middleware" in Plack): Plack::Middleware::Deflater. It’s a middleware to encode the response body in gzip or deflate, based on the "Accept−Encoding" HTTP request header.

Enable it as you would enable any Plack middleware. First you need to install Plack::Middleware::Deflater, then in the handler (usually app.psgi) edit it to use Plack::Builder, as described above:

    use Dancer2;
    use MyWebApp;
    use Plack::Builder;
    builder {
        enable 'Deflater';

To test if content compression works, trace the HTTP request and response before and after enabling this middleware. Among other things, you should notice that the response is gzip or deflate encoded, and contains a header "Content−Encoding" set to "gzip" or "deflate".

Creating a service

You can turn your app into proper service running in background using one of the following examples:

Using Ubic

Ubic is an extensible perlish service manager. You can use it to start and stop any services, automatically start them on reboots or daemon failures, and implement custom status checks.

A basic PSGI service description (usually in "/etc/ubic/service/application"):

    use parent qw(Ubic::Service::Plack);
    # if your application is not installed in @INC path:
    sub start {
        my $self = shift;
        $ENV{PERL5LIB} = '/path/to/your/application/lib';
        server => 'Starman',
        app => '/path/to/your/application/app.psgi',
        port => 5000,
        user => 'www−data',

Run "ubic start application" to start the service.

Using daemontools

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")

    # 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.psgi −p 5000

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:

Using Apache’s mod_proxy

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

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

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/

It is important for you to note that the Apache2 modules "mod_proxy" and "mod_proxy_http" must be enabled:

    $ a2enmod proxy
    $ a2enmod proxy_http

It is also important to set permissions for proxying for security purposes, below is an example.

    <Proxy *>
      Order allow,deny
      Allow from all

Using perlbal

"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 <>

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
    POOL my_dancers ADD
    POOL my_dancers ADD
    POOL my_dancers ADD
    CREATE SERVICE my_webapp
    SET listen          =
    SET role            = reverse_proxy
    SET pool            = my_dancers
    SET persist_client  = on
    SET persist_backend = on
    SET verify_backend  = on
    ENABLE my_webapp

Using balance

"balance" is a simple load-balancer from Inlab Software, available from <>.

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 80

Using Lighttpd

You can use Lighttp’s "mod_proxy":

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

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

Using Nginx

with Nginx:

    upstream backendurl {
        server unix:THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock;
    server {
      listen       80;
      server_name YOUR_HOST_HERE;
      access_log /var/log/YOUR_ACCESS_LOG_HERE.log;
      error_log  /var/log/YOUR_ERROR_LOG_HERE.log info;
      root YOUR_ROOT_PROJECT/public;
      location / {
        try_files $uri @proxy;
        access_log off;
        expires max;
      location @proxy {
            proxy_set_header Host $http_host;
            proxy_set_header X−Forwarded−Host $host;
            proxy_set_header X−Real−IP $remote_addr;
            proxy_set_header X−Forwarded−For $proxy_add_x_forwarded_for;
            proxy_pass       http://backendurl;

You will need plackup to start a worker listening on a socket :

    sudo −u www plackup −E production −s Starman −−workers=2 −l THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock −a bin/

A good way to start this is to use "daemontools" and place this line with all environments variables in the "run" file.

Using HAProxy

"HAProxy" is a reliable high-performance TCP/HTTP load balancer written in C available from <>.

Suppose we want to run an application at "" and would to use two backends listen on hosts "app−" and "app−".

Here is HAProxy configuration file (haproxy.conf):

        nbproc  1
        maxconn 4096
        user    nobody
        group   nobody
        # haproxy logs will be collected by syslog
        # syslog: unix socket path or tcp pair (ipaddress:port)
        log     /var/run/log local0
        # enable compression (haproxy v1.5−dev13 and above required)
        tune.comp.maxlevel  5
        log     global
        option  httpclose
        option  httplog
        option  dontlognull
        option  forwardfor
        option  abortonclose
        mode    http
        balance roundrobin
        retries 3
        timeout connect         5s
        timeout server          30s
        timeout client          30s
        timeout http−keep−alive 200m
        # enable compression (haproxy v1.5−dev13 and above required)
        compression algo gzip
        compression type text/html application/javascript text/css application/x−javascript text/javascript
    # application frontend (available at
        bind                  :80
        # modify request headers
        reqadd                X−Forwarded−Proto:\ http
        reqadd                X−Forwarded−Port:\ 80
        # modify response headers
        rspdel                ^Server:.*
        rspdel                ^X−Powered−By:.*
        rspadd                Server:\ Dethklok\ (Unix/0.2.3)
        rate−limit sessions   1024
        acl is−haproxy−stats  path_beg /stats
        # uncomment if you'd like to get haproxy usage statistics
        # use_backend haproxy   if is−haproxy−stats
        default_backend       dynamic
    # haproxy statistics (available at
    backend haproxy
        stats uri             /stats
        stats refresh         180s
        stats realm \ haproxy\ statistics
        # change credentials
        stats auth            admin1:password1
        stats auth            admin2:password2
        stats hide−version
        stats show−legends
    # application backends
    backend dynamic
        # change path_info to check and value of the Host header sent to application server
        option httpchk HEAD / HTTP/1.1\r\nHost:\
        server app1 app− check inter 30s
        server app2 app− check inter 30s

We will need to start the workers on each backend of our application. This can be done by starman utility:

    # on app−
    $ starman −−workers=2 −−listen :3000 /path/to/
    # on app−
    $ starman −−workers=2 −−listen :3000 /path/to/

Then start the haproxy itself:

    # check the configuration..
    $ sudo haproxy −c −f haproxy.conf
    # now really start it..
    $ sudo haproxy −f haproxy.conf

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

Running from Apache with Plack

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

        DocumentRoot /websites/
        <Directory /home/myapp/myapp>
            AllowOverride None
            Order allow,deny
            Allow from all
        <Location />
            SetHandler perl−script
            PerlResponseHandler Plack::Handler::Apache2
            PerlSetVar psgi_app /websites/
        ErrorLog  /websites/
        CustomLog /websites/ common

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

        SetEnv DANCER_ENVIRONMENT "production"

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 use the following example Apache configuration.

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
        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]

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.

Running on lighttpd ( CGI )
To run as a CGI app on lighttpd, just create a soft link to the "dispatch.cgi" script (created when you run "dancer −a MyApp") inside your system’s "cgi−bin" folder. Make sure "mod_cgi" is enabled.

    ln −s /path/to/MyApp/public/dispatch.cgi /usr/lib/cgi−bin/mycoolapp.cgi

Running on lighttpd (FastCGI)

Make sure "mod_fcgi" is enabled. You also must have FCGI installed.

This example configuration uses TCP/IP:

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

Launch your application:

    plackup −s FCGI −−port 5000 bin/app.psgi

This example configuration uses a socket:

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

Launch your application:

    plackup −s FCGI −−listen /tmp/fcgi.sock bin/app.psgi


Dancer Core Developers


This software is copyright (c) 2010 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


Dancer Core Developers


This software is copyright (c) 2015 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.