Serving static and media files with Dokku

October 25, 2018

Dokku is a great open source heroku like tool for managing sites. This post will show how to configure nginx to locally serve static and media files.

First, create a storage mapping so any media you upload files persist. Dokku recommends putting the file in /var/lib/dokku/data/storage/<app>/ so let's do that.

$ mkdir /var/lib/dokku/data/storage/<app>/
$ chown -R dokku:dokku /var/lib/dokku/data/storage/<app>/

Now create the mapping and have your site use the static folder.

$ dokku storage:help
Usage: dokku storage[:COMMAND]

Mount local volume / directories inside containers.

Additional commands:
    storage:list <app>                               List bind mounts for app's container(s) (host:container)
    storage:mount <app> <host-dir:container-dir>     Create a new bind mount
    storage:report [<app>] [<flag>]                  Displays a checks report for one or more apps
    storage:unmount <app> <host-dir:container-dir>   Remove an existing bind mount
$ dokku storage:mount <app> /var/lib/dokku/data/storage/<app>/:/app/static/

This creates the mapping but the files still need to be served from your app. We want nginx to serve the files do this instead, so configure it by creating a conf file

$ mkdir -p /home/dokku/<app>/nginx.conf.d
$ nano /home/dokku/<app>/nginx.conf.d/static.conf

with the contents

location /static/ {
    alias /var/lib/dokku/data/storage/<app>/;

You can add multiple locations if needed. Finally change the ownership and restart your app.

$ chown -R dokku:dokku /home/dokku/<app>/nginx.conf.d/static.conf
$ dokku ps:restart <app>

And now nginx should be serving your files!