Running Django with Docker

Leomahendradev


Why Use Docker for Django?

Docker is a containerization tool that simplifies development, deployment, and scaling. Running Django inside a Docker container helps maintain consistency across different environments, makes dependency management easier, and allows for seamless deployment.

Benefits of Using Docker for Django

  1. Consistency Across Environments

    • Docker ensures that the Django app runs the same way on every machine, eliminating the "works on my machine" problem.
  2. Simplified Dependency Management

    • No need to manually install Python, Django, PostgreSQL, Redis, or other dependencies—everything is packaged inside the container.
  3. Easy Deployment

    • Containers make it easy to deploy Django applications across different servers or cloud platforms without configuration issues.
  4. Isolation of Services

    • You can run Django, a database (PostgreSQL, MySQL), Redis, and other services in separate containers without conflicts.
  5. Scalability

    • Using Docker Compose or Kubernetes, you can scale different components of your Django application as needed.
  6. Faster Onboarding & Development

    • New developers can quickly set up a local development environment using docker-compose up.
  7. CI/CD Integration

    • Docker integrates well with CI/CD pipelines for automated testing and deployment.

Basic Usage of Docker with Django

1. Install Docker

Ensure Docker and Docker Compose are installed on your system.

2. Create a Dockerfile

This defines how the Django application should be built inside a container.

FROM python:3.11.7-slim-bookworm

ENV PYTHONUNBUFFERED 1

WORKDIR /backend

COPY . /backend

RUN python -m venv /opt/venv

RUN python3 -m venv /opt/venv && \
    /opt/venv/bin/pip install --upgrade pip && \
    /opt/venv/bin/pip install -r requirements.txt && \
    chmod +x /backend/entrypoint.sh

CMD [ "/backend/entrypoint.sh" ]

3. Creating a Django runner (entrypoint.sh) file

#!/bin/bash

APP_PORT=${PORT:-8000}

echo "Waiting for postgres..."
sleep 5
echo "PostgreSQL started"

echo "Migrating database..."
/opt/venv/bin/python manage.py makemigrations --noinput
/opt/venv/bin/python manage.py migrate --noinput
echo "Database migrated"

echo "Creating superuser..."
/opt/venv/bin/python manage.py createsuperuser || true
echo "Superuser created"

echo "Collecting static files..."
/opt/venv/bin/python manage.py collectstatic --noinput
echo "Static files collected"

echo "Starting server..."
/opt/venv/bin/gunicorn app.wsgi:application --bind "0.0.0.0:${APP_PORT}"

4. Run the Django App in Docker

docker-compose up --build

Next Steps

  • Set up Gunicorn and Nginx for production
  • Use environment variables to manage secrets
  • Implement Docker volumes for persistent storage
  • Deploy to AWS, DigitalOcean, or GCP using Docker

Post a Comment

0 Comments