Configuration and startup
The need: the same API must run on a developer machine with nothing to install, in dev with PostgreSQL and debug mode, and in prod safely, without any secret written in the code.
Related rules: Database · Secrets and access · Dev and prod environments
1. Debug mode and the secret key
api/trinity_api/settings.py, lines 19 to 41:
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / '.env')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
DEBUG = os.getenv('DEBUG', 'True').lower() == 'true'
SECRET_KEY = os.getenv('SECRET_KEY')
if not SECRET_KEY:
if not DEBUG:
raise ImproperlyConfigured(
'SECRET_KEY must be set when DEBUG is disabled.'
)
SECRET_KEY = 'dev-only-secret-key'
ALLOWED_HOSTS = [
host.strip()
for host in os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
if host.strip()
]load_dotenvreadsapi/.envif it exists. In dev and prod there is none: values come from the container's variables.DEBUGisTrueif the variable is missing. Handy locally, hence the need to setDEBUG: "False"in prod.SECRET_KEY: if it is missing andDEBUGis false, Django refuses to start. Prod therefore cannot be started with the development key by mistake.ALLOWED_HOSTS: the list of accepted domain names, comma-separated.
Why crash rather than use a default?
A default key in prod would sign sessions with a value known to everyone. A startup error is visible right away in the pipeline; a weak key is not.
2. The database
Lines 93 to 110:
if os.getenv('DB_HOST'):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DB_NAME'),
'USER': os.getenv('DB_USER'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': os.getenv('DB_HOST'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}A single criterion: DB_HOST. Set → PostgreSQL. Empty or missing → SQLite in api/db.sqlite3. The api:test job sets DB_HOST: "" to test on SQLite, without a PostgreSQL service.
3. The production image
api/Dockerfile.prod, second stage:
# Stage 2 : Image finale
FROM python:3.11-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PATH=/home/appuser/.local/bin:$PATH
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
RUN adduser --disabled-password --gecos "" appuser && chown appuser:appuser /app
COPY --from=builder /root/.local /home/appuser/.local
COPY --chown=appuser:appuser . .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "trinity_api.wsgi:application"]| Lines | Role |
|---|---|
| 19-20 | Only curl, for the health check. No build tools: psycopg2-binary ships precompiled |
| 22 | Creates appuser and gives it /app |
| 24-25 | Copies the installed libraries and the code, owned by appuser |
| 27 | Everything after runs as |
| 31-32 | The : curl on /health every 30 s |
| 34-35 | entrypoint.sh first, then Gunicorn with 3 workers |
This was not the case at first: line 22 only had adduser. The /app folder therefore belonged to root, and collectstatic crashed at startup with PermissionError: '/app/staticfiles'. The prod container never started. The fix fix(api): let appuser write the static files in the prod image added chown appuser:appuser /app.
4. Container startup
api/entrypoint.sh:
#!/bin/sh
set -e
echo "Exécution des migrations..."
python manage.py migrate --noinput
echo "Collecte des fichiers statiques..."
python manage.py collectstatic --noinput
exec "$@"migrateupdates the database before Gunicorn accepts requests.collectstaticcopies the admin's CSS and JS files intostaticfiles/.exec "$@"replaces the script with theCMDcommand, Gunicorn. Thanks toexec, Gunicorn receives Docker's stop signals directly and shuts down cleanly.
Why migrate at startup?
The migration always travels with the image that needs it: code expecting a missing column cannot be deployed. In exchange, two containers starting at the same time run migrate at the same time; with a single replica, that does not happen.
Pitfalls
Static files are not served in prod
Gunicorn does not serve staticfiles/. The Django admin therefore has no styling in prod. The JSON API is not affected. See Limits.
.env.example holds example values
dev-secret-key-change-in-production and trinity_pass are only examples. The real values are in the GitLab CI/CD variables. See Secrets and access.
What to remember
- All configuration comes from environment variables.
DB_HOSTchooses between PostgreSQL and SQLite.- In prod: non-root, migrations at startup, refusal to start without
SECRET_KEY.