Dancer...oyment(3pm)

okay bestie, buckle UP πŸ’– this right here is Dancer::Deployment, straight out of the User Contributed Perl Documentation (you know, the 3pm one), and it is literally the entire guide to getting your lil Dancer app off your laptop and out into the world. no gatekeeping. no cap. ✨

πŸ’– NAME πŸ’–

Dancer::Deployment β€” common ways to put your Dancer app into use πŸ¦‹

🌸 VERSION 🌸

version 1.3522 ✨

πŸŽ€ DESCRIPTION πŸŽ€

so <purple>Dancer</purple> was designed to be flexible, periodt, and that flexibility does not stop at the framework β€” it follows you all the way to how you deploy your Dancer app. πŸ’…


🌈 Running as a cgi-script (or fast-cgi) under Apache

in the spirit of ultimate deployment flexibility, your Dancer app can be run as a plain old cgi-script out-of-the-box, with literally no extra web server configuration needed. 🎁 your web server just has to recognize .cgi files and be able to serve Perl scripts. heads up though: the Perl module Plack::Runner is required. πŸ”‘

start by adding this to your apache configuration (httpd.conf or sites-available/*site*):

<VirtualHost *:80>
    ServerName www.example.com

    # /srv/www.example.com is the root of your
    # dancer application
    DocumentRoot /srv/www.example.com/public

    ServerAdmin you@example.com

    <Directory "/srv/www.example.com/public">
       AllowOverride None
       Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
       Order allow,deny
       Allow from all
       AddHandler cgi-script .cgi
    </Directory>

    ScriptAlias / /srv/www.example.com/public/dispatch.cgi/

    ErrorLog  /var/log/apache2/www.example.com-error.log
    CustomLog /var/log/apache2/www.example.com-access_log common
</VirtualHost>

now you can access your dancer application URLs as if you were using the embedded web server:

http://localhost/

this option is a <mint>no-brainer</mint> β€” easy to setup, low maintenance β€” but bestie, brace yourself: it serves requests slower than all other options. πŸ’πŸ’€

you can use the very same technique to deploy with FastCGI, you just swap out the lines:

AddHandler cgi-script .cgi

...

ScriptAlias / /srv/www.example.com/public/dispatch.cgi

to:

AddHandler fastcgi-script .fcgi

...

ScriptAlias / /srv/www.example.com/public/dispatch.fcgi

πŸš€ Running stand-alone

at the absolute simplest, your Dancer app can run standalone, operating as its own webserver using HTTP::Server::Simple::PSGI. main character energy, honestly. πŸ‘‘

simply fire up your app:

$ perl bin/app.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. 🌍❌

πŸͺ Running on Perl webservers with plackup

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

  • Starman β€” <yellow>Starman</yellow> is a high performance web server, with support for preforking, signals and more. πŸ’ͺ
  • Twiggy β€” <yellow>Twiggy</yellow> is an <cyan>AnyEvent</cyan> web server, it's light and fast. πŸͺΆ
  • Corona β€” <yellow>Corona</yellow> is a <cyan>Coro</cyan> based web server.
⚠️ WARNING: <yellow>Dancer</yellow>'s use of global variables and <cyan>Coro</cyan>'s threaded behaviors can cause some unexpected behaviors. see this GitHub issue https://github.com/PerlDancer/Dancer/issues/929 for more details. unless you have really, really strongly compelling reasons to use Corona, consider using <yellow>Twiggy</yellow> or <yellow>Starman</yellow> instead. πŸ™ˆ

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

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

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

πŸ—œοΈ Enabling content compression

content compression (gzip, deflate) can be easily enabled via a Plack middleware (see Plack#Plack::Middleware): Plack::Middleware::Deflater. it's a middleware to encode the response body in gzip or deflate, based on the Accept-Encoding HTTP request header. so slay. πŸ”₯

enable it exactly like you'd enable any Plack middleware. first you need to install Plack::Middleware::Deflater, then in the configuration file (usually environments/development.yml), add these lines:

plack_middlewares:
  -
    - Plack::Middleware::Deflater
    - ...

these lines tell Dancer to add Plack::Middleware::Deflater to the list of middlewares to pass to Plack::Builder, when wrapping the Dancer app. the syntax is :

  • as key: the name of the Plack middleware to use
  • as value: the options to pass it as a list. in our case, there is no option to specify to Plack::Middleware::Deflater, so we use an empty YAML list. πŸŽ€

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. πŸ”βœ¨

☁️ Hosting on DotCloud

the simplest way to achieve this is to push your main application directory to dotcloud with your bin/app.pl file copied to (or symlinked from) app.psgi. 🫢

beware that the dotcloud service enforces one environment only, named deployment. so instead of having environments/development.yml or environments/production.yml you must have a file named environments/deployment.yml. 😀

also make sure that your Makefile.PL (or other dependency mechanism) includes both Dancer and Plack::Request. πŸ“

the default in-memory session handler won't work, and instead you should switch to something persistent. edit config.yml to change session: 'Simple' to (for example) session: 'YAML'. πŸ’Ύ

πŸ”§ In case you have issues with Template::Toolkit on Dotcloud

if you use the Template::Toolkit and its INCLUDE or PROCESS directives, you might need to add the search path of your view files to the config. this is probably going to be something like INCLUDE_PATH: '/home/dotcloud/current/views' in config.yml.

an alternative implementation is to use a variation of the above Plack::Builder template:

use Plack::Builder;
use Dancer ':syntax';
use Dancer::Handler;
use lib 'lib';

my $app1 = sub {
    setting appdir => '/home/dotcloud/current';
    load_app "My::App";
    Dancer::App->set_running_app("My::App");
    my $env = shift;
    Dancer::Handler->init_request_headers($env);
    my $req = Dancer::Request->new(env => $env);
    Dancer->dance($req);
};

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

this also supports hosting multiple apps, but you probably also need to specify the specific Environment configuration to use in your application. πŸ‘€

when mounting under a path on dotcloud, as in the above example, always create links using the uri_for() method for Dancer routes, and a uri_base variable for static content as shown in Dancer::Cookbook. this means whatever base path your app is mounted under, links and form submissions will continue to work. πŸ’–

πŸ› οΈ Creating a service

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

🌟 Using Ubic

Ubic is a polymorphic 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);

__PACKAGE__->new(
    server => 'Starman',
    app => '/path/to/your/application/app.pl',
    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)

#!/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

πŸŒ‰ 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:

<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/
<Location /mywebapp/>
    RequestHeader set Request-Base /mywebapp
</Location>

the HTTP header Request-Base is taken into account by Dancer, only when behind_proxy setting is set to true. πŸ‘€

it is important for you to note that the Apache2 modules mod_headers, mod_proxy and mod_proxy_http must be enabled.

a2enmod headers
a2enmod proxy
a2enmod proxy_http

note that Apache does not pass protocol information when proxying, so if needed then you will need to set it manually in your Apache config:

RequestHeader set X_FORWARDED_PROTO "https"

it is also important to set permissions for proxying for security purposes πŸ”, below is an example.

<Proxy *>
  Order allow,deny
  Allow from all
</Proxy>

πŸ¦‹ 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 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 my_webapp

βš–οΈ Using balance

πŸ“ ...and that is exactly where this half of the page cuts off, bestie β€” `part 2 has the rest and it's right there waiting for you πŸ’–

So balance is a cute lil simple load-balancer from Inlab Software, and you can grab it over at http://www.inlab.de/balance.html πŸ’–.

You can literally just use it to hand requests to one standalone Dancer app. OR β€” and this is the fun part β€” you could run several instances of your Dancer app, on the same machine or across several machines, and have a box running balance spread the requests between them. That's some serious heavy-traffic handling, bestie. Main character load balancing. πŸ‘‘

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

🌸 Using Lighttpd 🌸

You can use lighttpd's mod_proxy:

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

This config will proxy all requests to the /application path over to the path / on localhost:3000. slay πŸ¦‹

πŸŽ€ 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_set_header X-Forwarded-Proto $scheme;
        proxy_pass       http://backendurl;
  }

}

You're gonna need plackup to start a worker that listens on a socket, bestie:

cd YOUR_PROJECT_PATH
sudo -u www plackup -E production -s Starman --workers=2 -l THE_PATH_OF_YOUR_PLACKUP_SOCKET_HERE.sock -a bin/app.pl

A good way to start this is with daemontools, dropping that line (with all the environment variables) into the run file. periodt πŸ’…

🧚 Using HAProxy 🧚

HAProxy is a reliable high-performance TCP/HTTP load balancer written in C, available from http://haproxy.1wt.eu/. iconic honestly.

So say we wanna run an application at app.example.com:80 and use two backends listening on hosts app-be1.example.com:3000 and app-be2.example.com:3000. Here's the HAProxy config file (haproxy.conf):

global
    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
    daemon
    # enable compression (haproxy v1.5-dev13 and above required)
    tune.comp.maxlevel  5

defaults
    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 http://app.example.com)
frontend app.example.com
    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 http://app.example.com/stats)
backend haproxy
    stats uri             /stats
    stats refresh         180s
    stats realm           app.example.com\ 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:\ app.example.com
    server app1 app-be1.example.com:3000 check inter 30s
    server app2 app-be2.example.com:3000 check inter 30s

We gotta start the workers on each backend of our application too. You can do that with the starman utility:

# on app-be1.example.com
$ starman --workers=2 --listen :3000 /path/to/app.pl
# on app-be2.example.com
$ starman --workers=2 --listen :3000 /path/to/app.pl

Then start haproxy itself, obviously:

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

πŸ“ Plackup Chef Cookbook πŸ“

There's a psgi chef cookbook that supports Dancer (and Catalyst too, bestie) written by Alexey Melezhik, and it lives at http://community.opscode.com/cookbooks/psgi. go off πŸ’œ

πŸ”₯ Running from Apache πŸ”₯

You can run your Dancer app from Apache using the examples below. let's get into it.

✨ Running from Apache with Plack ✨

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

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

    <Directory /websites/myapp.example.com>
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>

    <Location />
        SetHandler perl-script
        PerlResponseHandler 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 for your application (production or development), you can set it like this:

<VirtualHost>
    ...
    SetEnv DANCER_ENVIRONMENT "production"
    ...
</VirtualHost>
NOTE: only a single Dancer application can be deployed using the Plack::Handler::Apache2 method. Multiple Dancer applications will NOT work properly β€” the routes get mixed-up between the applications. πŸ’€

It's recommended to start each app with plackup using your favorite server (Starman, for example) and then put a web server (Apache, Nginx, Perlbal, etc.) as a frontend server for both apps using reverse proxy (HTTP based, no fastcgi). that's the move fr fr.

🌈 Running from Apache under appdir 🌈

If you wanna deploy multiple applications under the same VirtualHost β€” like one application per directory β€” you can do this:

This example uses the FastCGI dispatcher that comes with Dancer, but you should be able to adapt it to 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. (iykyk πŸ™ˆ)

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

And of course β€” if your Apache configuration allows it β€” you can drop the RewriteRules into a .htaccess file right inside the application's directory, which means you can add a new application without ever touching the Apache configuration. obsessed. 🫢

🌸 Running on lighttpd (CGI) 🌸

To run as a CGI app on lighttpd, just make 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" => "127.0.0.1",
                "port" => "5000",
                "check-local" => "disable",
            )
        )
    )
}

Launch your application:

plackup -s FCGI --port 5000 bin/app.pl

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.pl

πŸ‘‘ AUTHOR πŸ‘‘

Dancer Core Developers. icons only, we love them πŸ’–

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.


and that's a wrap bestie πŸŽ€ this whole thing is perl v5.40.1, dated 2026-05-05 β€” Dancer's deployment guide, slayed from start to finish. mwah πŸ’…βœ¨

πŸ“¦ where this page comes from