Docker helps you package your Django app with everything it needs to run. This makes it easy to share and run your app anywhere without setup problems.
0
0
Docker containerization in Django
Introduction
You want to run your Django app on different computers without installing Python or dependencies each time.
You need to share your Django app with teammates or deploy it to a server quickly.
You want to keep your app environment consistent to avoid "it works on my machine" issues.
You want to run multiple apps or services together without conflicts.
You want to test your Django app in a clean environment every time.
Syntax
Django
FROM python:3.12-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
FROM sets the base image with Python installed.
WORKDIR sets the folder inside the container where commands run.
Examples
Basic Dockerfile to run a Django app on port 8000.
Django
FROM python:3.12-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Dockerfile using Gunicorn for production-ready Django server.
Django
FROM python:3.12-slim ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["gunicorn", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]
Sample Program
This Dockerfile sets up a container to run a Django development server accessible on all network interfaces at port 8000.
Django
FROM python:3.12-slim WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
OutputSuccess
Important Notes
Remember to expose port 8000 in your Docker run command to access the app from your browser.
Use a .dockerignore file to avoid copying unnecessary files into the container.
For production, use a proper WSGI server like Gunicorn instead of Django's development server.
Summary
Docker packages your Django app and its environment together.
This makes running and sharing your app easy and consistent.
Use a Dockerfile to define how your app is built and started inside a container.