Django and Gunicorn with Docker: Step-by-Step
In this article
This guide walks you through containerizing a Django application with Gunicorn as the WSGI server using Docker. You’ll end up with a production-ready setup that runs your Django project in a container, served by Gunicorn, and ready to be deployed to any Docker‑capable host.
What You'll Need
- Docker installed on your machine (version 20.10 or later recommended).
- Docker Compose (usually included with Docker Desktop, but can be installed separately on Linux).
- A basic Django project already created (or you can follow along with a simple one).
- Basic familiarity with the command line and Django project structure.
Step-by-Step
-
Prepare your Django project
Ensure your Django project has arequirements.txtfile listing all Python dependencies. If you don’t have one, create it with at leastDjangoandgunicorn. Example:Django==5.0.6 gunicorn==22.0.0
-
Create a Dockerfile
In your project root, create a file namedDockerfile(no extension). Use a slim Python base image to keep the image small. A minimal example:FROM python:3.12-slim ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myproject.wsgi:application"]
Replacemyprojectwith your Django project’s name (the folder containingwsgi.py). -
Create a .dockerignore file
To keep the build context clean and avoid copying unnecessary files, create a.dockerignorefile in the same directory. Add at least:__pycache__/ *.pyc .env .git venv/
-
Set up environment variables
For security, do not hardcode secrets in your code. Use environment variables. In yoursettings.py, read them like this:import os SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'fallback-dev-key') DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True' ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', 'localhost').split(',') -
Create a docker-compose.yml file
For local development and easy orchestration, create adocker-compose.yml:services: web: build: . ports: - "8000:8000" environment: - DJANGO_SECRET_KEY=your-secret-key - DJANGO_DEBUG=False - DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1 volumes: - .:/app command: gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application -
Build and run the container
From your project root, run:docker-compose up --build
This builds the image and starts the container. If everything works, you should see Gunicorn booting and serving on port 8000. -
Test your application
Open a browser and go tohttp://localhost:8000. You should see your Django app. If you see a “Bad Request (400)” error, check yourALLOWED_HOSTSsetting. -
Run database migrations
If your app uses a database, you need to run migrations inside the container. First, find your container ID withdocker ps, then run:docker exec -it <container_id> python manage.py migrate
Or, if you prefer, add a command in your compose file to run migrations before starting Gunicorn (advanced). -
Create a superuser (optional)
To access the Django admin, create a superuser:docker exec -it <container_id> python manage.py createsuperuser
-
Stop and clean up
When done, stop the container withCtrl+Cordocker-compose down. To remove the image as well, usedocker-compose down --rmi all.
Common Mistakes
- Forgetting to update ALLOWED_HOSTS – Django will throw a 400 error if the host isn’t in the list. Always set it via environment variable.
- Running with DEBUG=True in production – This exposes sensitive information. Keep DEBUG=False.
- Hardcoding the database host – If you use a database container, use the service name as the host (e.g., “db” in compose).
- Not using .dockerignore – This can bloat your image with local files like .env or .git, which is a security risk.
- Binding Gunicorn to 127.0.0.1 – Inside a container, you must bind to 0.0.0.0 so the port is accessible from outside.
Tips
- Use a non‑root user inside the container for better security. Add these lines to your Dockerfile:
RUN addgroup --system app && adduser --system --ingroup app app USER app
- Pin your Python package versions to avoid unexpected updates breaking your app.
- Use multi‑stage builds if you need build tools (like compilers) for some packages, then copy only the runtime artifacts.
- For production, consider using a reverse proxy like Nginx in front of Gunicorn to serve static files and handle SSL.
- Use Docker Compose’s
depends_onto ensure your database starts before your web app, but note it only waits for the container to start, not for the DB to be ready.
Troubleshooting
- “Bad Request (400)” – Add the domain or IP you’re accessing from to
ALLOWED_HOSTS. - “ModuleNotFoundError: No module named ‘myproject’” – Make sure your
WORKDIRandCOPYcommands place the Django project in the correct location, and that you’re referencing the right WSGI module. - Port already in use – Change the host port in the compose file (e.g.,
"8001:8000") or stop the process using the port. - Database connection refused – If using a separate DB container, ensure the host is set to the service name and that the DB is ready. You may need to add a healthcheck or a retry loop.
- Changes not reflecting – If you’re using volumes, make sure you’re not caching old code. Rebuild with
--buildand ensurePYTHONDONTWRITEBYTECODEis set. - Gunicorn won’t start – Check logs with
docker logs <container_id>. Common causes: missing environment variables, syntax errors in settings, or incorrect WSGI path.
Frequently Asked Questions
Do I need Gunicorn for development?
No. Django’s built‑in development server is fine for local testing. Gunicorn is a production WSGI server that’s more robust and performant. You can still use it locally to mimic production.
How do I serve static files with Gunicorn?
Gunicorn does not serve static files efficiently. In production, use a reverse proxy like Nginx to serve static files directly. For local testing, you can use Django’s runserver or configure whitenoise to serve static files from Python.
Can I use Docker without Docker Compose?
Yes. You can build and run the container manually with docker build and docker run. Compose just simplifies multi‑container setups and configuration.
How do I scale Gunicorn workers?
Set the number of workers in the Gunicorn command, e.g., --workers 3. A common formula is 2 × CPU cores + 1, but you can adjust based on your app’s needs.
What’s the difference between CMD and ENTRYPOINT in the Dockerfile?
CMD provides default arguments that can be overridden when running the container. ENTRYPOINT defines the main process and is harder to override. For Gunicorn, either works, but using CMD is simpler if you want to override the command during development.
How do I debug inside a running container?
You can open a shell inside the container with docker exec -it <container_id> /bin/bash. From there, you can run Django management commands, inspect files, or test connections.