35
After confirming with Heroku support, this does indeed appear to be a bit of a catch-22.
The solution was to put collectstatic
in the Dockerfile so that it runs during build time and the files persist.
We got around not having a secret key config var by setting a default secret key using the get_random_secret_key
function from Django.
The run phase uses the secret key from the Heroku config vars, so we aren’t actually changing the secret key every time — the default only applies to the build process. collectstatic
doesn’t index on the secret key, so this is fine.
In settings.py
from django.core.management.utils import get_random_secret_key
...
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', default=get_random_secret_key())
8
I don’t use heroku so can’t test, but you should be able to run collect static before you run the app;
Dockerfile
# Pull base image
FROM python:3.7-slim
# Set environment varibles
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code/
# Install dependencies
RUN pip install pipenv
COPY Pipfile Pipfile.lock .
RUN pipenv install --system
# Copy project
COPY . .
# Collect static files
RUN python manage.py collectstatic --noinput
# run gunicorn
CMD gunicorn hello_django.wsgi:application --bind 0.0.0.0:$PORT
You could also not run collectstatic
in your dockerfile, or event run the application because these can be ran by heroku.yml
, for example;
build:
docker:
web: Dockerfile
config:
DJANGO_SETTINGS_MODULE: project.settings
run:
web: gunicorn backend.config.wsgi:application --bind 0.0.0.0:$PORT
release:
image: web
command:
- python manage.py collectstatic --noinput
You also shouldn’t need to mkdir
for your working directory. Just set WORKDIR /code/
early in your dockerfile and after that things will run based on that directory.
There’s a decent article on this here; https://testdriven.io/blog/deploying-django-to-heroku-with-docker/
- [Django]-Django equivalent of PHP's form value array/associative array
- [Django]-Why is using thread locals in Django bad?
- [Django]-Django template comparing string
0
You can prefix commands with dummy environment variables
RUN DJANGO_SECRET_KEY=secret python manage.py collectstatic --no-input
- [Django]-Update to Django 1.8 – AttributeError: django.test.TestCase has no attribute 'cls_atomics'
- [Django]-Naming convention for Django URL, templates, models and views
- [Django]-Django 1.11 TypeError context must be a dict rather than Context