How to configure an existing Django application for deployment on Divio#

This document will take you step-by-step through the tasks required to set up a portable, vendor-neutral application, for deployment to Divio using Docker. The application architecture we adopt is in line with Twelve-factor design principles.

Use the guide to help you adapt an existing application for Docker or check that your existing Docker application will run on Divio. The exact steps you need to take will depend on details of your application.

The steps here should work with any Django application, and include configuration for:

Prerequisites#

  • Your application needs to be managed in a Git repository, hosted on Divio application or your preferred Git host.

  • You need to be familiar with the basics of the Divio platform and Docker, and have Docker and the Divio CLI installed on your machine. If not, please follow one of our tutorials.

  • You need to have at least a minimal working application ready to be deployed, whether it is Docker-ready already or not.

If you don’t already have a working Django application#

See How to create a Django application with our quickstart repository.

The Dockerfile - define how to build the application#

The application needs a Dockerfile at the root of repository, that defines how to build the application. The Dockerfile starts by importing a base image.

For a Django application, you can use:

FROM python:3.8

Here, python:3.8 is the name of the Docker base image. We cannot advise on what base image you should use; you’ll need to use one that is in-line with your application’s needs. However, once you have a working set-up, it’s good practice to move to a more specific base image - for example python:3.8.1-slim-buster.

Install system-level dependencies#

The Dockerfile needs to install any system dependencies required by the application. For example, if your chosen base image is Debian-based, you might run:

RUN apt-get update && apt-get install -y <list of packages>

WORKDIR#

We recommend setting up a working directory early on in the Dockerfile before you need to write any files, for example:

# set the working directory
WORKDIR /app
# copy the repository files to it
COPY . /app

Install application-level dependencies#

The next step is to install application-level dependencies.

# install dependencies listed in the repository's requirements file
RUN pip install -r requirements.txt

Any requirements should be pinned as firmly as possible.

Use the output from pip freeze to get a full list of dependencies. Assuming you use the methods we recommend below for configuring settings and handling storage, you will need to include some of the following (it’s up to you to choose the right versions of course):

django>=3.1,<3.2
dj-database-url==0.5.0
django-storage-url==0.9.2
whitenoise==5.2.0
boto3==1.14.49

# Select one of the following for the database
psycopg2==2.8.5
mysqlclient==2.0.1

# Select one of the following for the gateway server
uwsgi==2.0.19.1
uvicorn==0.11.8
gunicorn==20.0.4

File-building operations#

If the application needs to perform any build operations to generate files, they should be run in the Dockerfile so that they are built into the image. This could include compiling or collecting JavaScript or CSS, for example, and can make use of frameworks that do this work.

A minimal Django application needs to have its static files collected:

RUN python manage.py collectstatic --noinput

EXPOSE and CMD#

EXPOSE informs Docker that the container listens on the specified ports at runtime; typically, you’d need:

EXPOSE 80

Launch a server running on port 80 by including a CMD at the end of the Dockerfile.

# Select one of the following application gateway server commands
CMD uwsgi --http=0.0.0.0:80 --module=myapp.wsgi
CMD gunicorn --bind=0.0.0.0:80 --forwarded-allow-ips="*" myapp.wsgi
CMD uvicorn --host=0.0.0.0 --port=80 myapp.asgi:application

You’ll need to change myapp appropriately.

Use CMD, not ENTRYPOINT, to start the server

Using CMD provides a default way to start the server, that can also be overridden. This is useful when working locally, where often we would use the docker-compose.yml to issue a startup command that is more suited to development purposes. It also allows our infrastructure to override the default, for example in order to launch containers without starting the server, when some other process needs to be executed.

An ENTRYPOINT that starts the server would not allow this.

If you are using a Docker entrypoint script, it’s good practice to conclude it with exec "$@", so that any commands passed to the container will be executed as expected.

Access to environment and services#

Warning

During the build process, Docker has no access to the application’s environment or services.

This means you cannot run database operations such as database migrations during the build process. Instead, these should be handled later as release commands.

Configuring your application#

Your application will require configuration. You may be used to hard-coding such values in the application itself - though you can do this on Divio, we recommend not doing it. Instead, all application configuration (for access to services such as the database, security settings, etc) should be managed via environment variables.

Divio provides services such as database and media. To access them, your application will need the credentials. For each service in each environment, we provide an environment variable containing the values required to access it. This variable is in the form:

schema://<user name>:<password>@<address>:<port>/<name>

Your application should:

  • read the variables

  • parse them to obtain the various credentials they contain

  • configure its access to services using those credentials

We also provide environment variables for things like security configuration.

Helper modules#

In your Django settings file, import some helper modules to handle the environment variables:

import os
import dj_database_url
from django_storage_url import dsn_configured_storage_class

Security settings#

Some security-related settings such as ALLOWED_HOSTS are required in Django. The cloud environments will provide some of these values as environment variables where appropriate; in all cases the configuration we provide in this example will fall back to safe values if an environment variable is not provided:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', '<a string of random characters>')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG') == "True"

DIVIO_DOMAIN = os.environ.get('DOMAIN', '')
DIVIO_DOMAIN_ALIASES = [
    d.strip()
    for d in os.environ.get('DOMAIN_ALIASES', '').split(',')
    if d.strip()
]
DIVIO_DOMAIN_REDIRECTS = [
    d.strip()
    for d in os.environ.get('DOMAIN_REDIRECTS', '').split(',')
    if d.strip()
]

ALLOWED_HOSTS = [DIVIO_DOMAIN] + DIVIO_DOMAIN_ALIASES + DIVIO_DOMAIN_REDIRECTS

# Redirect to HTTPS by default, unless explicitly disabled
SECURE_SSL_REDIRECT = os.environ.get('SECURE_SSL_REDIRECT') != "False"

Database#

Database credentials, if required, are provided in a DATABASE_URL environment variable. When a database (and therefore the environment variable) are not available (for example during the Docker build phase) the application should fall back safely, to a null database option or to an in-memory database (e.g. using sqlite://:memory:).

See the Django guide for a concrete example.

For Django, we recommend:

# Configure database using DATABASE_URL; fall back to sqlite in memory when no
# environment variable is available, e.g. during Docker build
DATABASE_URL = os.environ.get('DATABASE_URL', 'sqlite://:memory:')

DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}

Static files#

There are numerous options for static file serving. You can opt to serve them directly from the application, or to configure the web server/gateway server to handle them.

For our recommended general-purpose static file serving configuration, first, add the WhiteNoiseMiddleware to the list of MIDDLEWARE, after the SecurityMiddleware:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    [...]
]

and then apply:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Media#

If your application needs to handle generated or user-uploaded media, it should use a media object store.

Media credentials are provided in DEFAULT_STORAGE_DSN. See how to parse the storage DNS to obtain the credentials for the media object stores we provide. Your application needs to be able to use these credentials to configure its storage.

When working in the local environment, it’s convenient to use local file storage instead (which can be also be configured using a variable provided by the local environment).

Modern application frameworks such as Django make it straightforward to configure an application to use storage on multiple different backends, and are supported by mature libraries that will let you use a Divio-provided S3 or MS Azure storage service as well as local file storage.

For Django, we suggest using:

# Media files
# DEFAULT_FILE_STORAGE is configured using DEFAULT_STORAGE_DSN

# read the setting value from the environment variable
DEFAULT_STORAGE_DSN = os.environ.get('DEFAULT_STORAGE_DSN')

# dsn_configured_storage_class() requires the name of the setting
DefaultStorageClass = dsn_configured_storage_class('DEFAULT_STORAGE_DSN')

# Django's DEFAULT_FILE_STORAGE requires the class name
DEFAULT_FILE_STORAGE = 'myapp.settings.DefaultStorageClass'

# only required for local file storage and serving, in development
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join('/data/media/')

(Note that the DEFAULT_FILE_STORAGE assumes your Django application was named myapp.)

Local file storage is not a suitable option

Your code may expect, by default, to be able to write and read files from local file storage (i.e. files in the same file-space as belonging to the application).

This will not work well on Divio or any similar platform. Our stateless containerised application model does not provide persistent file storage. Instead, your code should expect to use a dedicated file storage; we provide AWS S3 and MS Azure blob storage options.

Other values#

You may need to make use of other variables for your application - take every opportunity to make use of the provided variables so that your codebase can contain as little as configuration as possible.

Add a URL pattern for serving media files in local development#

You will need to edit the application’s urls.py (e.g. myapp/urls.py):

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns.extend(static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))

Local container orchestration with docker-compose.yml#

What’s described above is fundamentally everything you need in order to deploy your application to Divio. You could deploy your application with that alone.

However, you would be missing out on a lot of value. Being able to build and then run the same application, in a very similar environment, locally on your own computer before deploying it to the cloud makes development and testing much more productive. This is what we’ll consider here.

docker-compose.yml is only used locally

Cloud deployments do not use Docker Compose. Nothing that you do here will affect the way your application runs in a cloud environment. See docker-compose.yml.

Create a docker-compose.yml file, for local development purposes. This will replicate the web image used in cloud deployments, allowing you to run the application in an environment as close to that of the cloud servers as possible. Amongst other things, it will allow the application to use a Postgres or MySQL database (choose the appropriate lines below) running in a local container, and provides convenient access to files inside the containerised application.

Take note of the highlighted lines below; some require you to make a choice.

version: "2.4"
services:
  web:
    # the application's web service (container) will use an image based on our Dockerfile
    build: "."
    # map the internal port 80 to port 8000 on the host
    ports:
      - "8000:80"
    # map the host directory to app (which allows us to see and edit files inside the container)
    volumes:
      - ".:/app:rw"
      - "./data:/data:rw"
    # the default command to run whenever the container is launched
    command: python manage.py runserver 0.0.0.0:80
    # a link to database_default, the application's local database service
    links:
      - "database_default"
    env_file: .env-local

  database_default:
    # Select one of the following db configurations for the database
    image: postgres:13.5-alpine
    environment:
      POSTGRES_DB: "db"
      POSTGRES_HOST_AUTH_METHOD: "trust"
      SERVICE_MANAGER: "fsm-postgres"
    volumes:
      - ".:/app:rw"

    image: mysql:5.7
    environment:
      MYSQL_DATABASE: "db"
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
      SERVICE_MANAGER: "fsm-mysql"
    volumes:
      - ".:/app:rw"
      - "./data/db:/var/lib/mysql"
    healthcheck:
        test: "/usr/bin/mysql --user=root -h 127.0.0.1 --execute \"SHOW DATABASES;\""
        interval: 2s
        timeout: 20s
        retries: 10

Local configuration using .env-local#

As you will see above, the web service refers to an env_file containing the environment variables that will be used in the local development environment.

Divio cloud applications include a number of environment variables as standard. In addition, user-supplied variables may be applied per-environment.

If the application refers to its environment for variables to configure database, storage or other services, it will need to find those variables even when running locally. On the cloud, the variables will provide configuration details for our database clusters, or media storage services. Clearly, you don’t have a database cluster or S3 instance running on your own computer, but Docker Compose can provide a suitable database running locally, and you can use local file storage while developing.

Create a .env-local file. In this you need to provide some environment variables that are suitable for the local environment. The example below assumes that your application will be looking for environment variables to configure its access to a Postgres or MySQL database, and for local file storage:

# Select one of the following for the database
DATABASE_URL=postgres://postgres@database_default:5432/db
DATABASE_URL=mysql://root@database_default:3306/db

DEFAULT_STORAGE_DSN=file:///data/media/?url=%2Fmedia%2F
DJANGO_DEBUG=True
DOMAIN_ALIASES=localhost, 127.0.0.1
SECURE_SSL_REDIRECT=False

With this, you have the basics for a Dockerised application that can equally effectively be deployed in a production environment or run locally, using environment variables for configuration in either case.

Building and running#

Build with Docker#

Now you can build the application containers locally:

docker-compose build

Run database migrations if required#

The new database will need to be migrated before you can start any application development work:

docker-compose run web python manage.py migrate

And create a Django superuser:

docker-compose run web python manage.py createsuperuser

Or, you can import the database content from an existing database - see How to interact with your application’s database.

Check the local site#

You may need to perform additional steps such as migrating a database. To run a command manually inside the Dockerised environment, precede it with docker-compose run web. (For example, to run Django migrations: docker-compose run web python manage.py migrate.)

To start up the site locally to test it:

docker-compose up

Access the site at http://127.0.0.1:8000/. You can set a different port in the ports option of docker-compose.yml.

Git#

Your code needs to be in a Git repository in order to be deployed on Divio.

You will probably want to exclude some files from the Git repository, so check your .gitignore and ensure that nothing will be committed that you don’t want included.

If using the suggestions above, you’ll probably want:

# Python
*.pyc
*.pyo
db.sqlite3

# Django
/staticfiles

# Divio
.divio
/data.tar.gz
/data


# OS-specific patterns - add your own here
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes

Additional notes#

See Working with our recommended Django application configuration for further guidance.

Deployment#

Your application is ready for deployment on our cloud platform. The basic steps are:

  • create an application on the Divio Control Panel, with any required services

  • push your code/connect your Git repository

  • deploy one or more cloud environments

These steps are covered in more detail in Deploy your application to Divio.