Table of Contents
Deploying Django applications can be complex, but using Docker and Gunicorn simplifies the process significantly. This guide provides a step-by-step workflow to help developers deploy their Django projects efficiently and reliably.
Prerequisites
- Basic knowledge of Django framework
- Docker installed on your machine
- Python and pip installed
- Understanding of Gunicorn server
Step 1: Prepare Your Django Application
Ensure your Django project is ready for deployment. This includes setting ALLOWED_HOSTS appropriately, configuring static and media files, and verifying that your application runs correctly locally.
Step 2: Create a Dockerfile
Create a Dockerfile in your project directory with the following content:
Dockerfile
FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --upgrade pip && pip install -r requirements.txt
COPY . /app/
CMD ["gunicorn", "your_project_name.wsgi:application", "--bind", "0.0.0.0:8000"]
Step 3: Define Requirements
Create a requirements.txt file that includes:
- Django
- gunicorn
- any other dependencies your project needs
Step 4: Build the Docker Image
In your project directory, run the following command to build your Docker image:
docker build -t my-django-app .
Step 5: Run the Docker Container
Start your container with:
docker run -d -p 8000:8000 --name django_container my-django-app
Step 6: Verify Deployment
Open your browser and navigate to http://localhost:8000. Your Django application should be live and accessible.
Additional Tips
- Use environment variables for sensitive settings.
- Configure static files collection with
python manage.py collectstatic. - Implement Docker Compose for multi-container setups.
- Set up a reverse proxy like Nginx for production environments.
By following this workflow, deploying your Django application with Docker and Gunicorn becomes a streamlined process, ensuring consistency across development and production environments.