Django Portfolio Journal

Creating a Dockerfile


A Dockerfile is designed to containerize a Django web application, creating a consistent and isolated environment for deployment.

The file starts by defining a lightweight base image, ensuring Python compatibility with Django. System dependencies and utilities are installed to support Python packages.

Next, the Dockerfile sets the working directory, often /app, where all application files will reside. It copies the requirements.txt file into the container and runs pip install -r requirements.txt to install Python dependencies, optimizing the build by installing packages before adding application code, thus leveraging Docker’s caching mechanism to speed up rebuilds.

The Dockerfile then copies the entire Django project into the container’s working directory, ensuring the application’s code, settings, and assets are included. It usually sets environment variables such as PYTHONUNBUFFERED=1 to handle output buffering, and PYTHONDONTWRITEBYTECODE=1 which can improve logging in Docker.

To finalize the setup, the Dockerfile may include commands to collect static files via python manage.py collectstatic for production environments. Additionally, it may expose a port, typically 8000, and set the default command to gunicorn, specifying myproject.wsgi:application as the application entry point.

FROM python:3.11-slim

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

COPY ./requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt

COPY . .

EXPOSE 8000

RUN python manage.py collectstatic --noinput
RUN python manage.py migrate --noinput

ENTRYPOINT ["gunicorn", "portfolio.wsgi:application", "--bind", "0.0.0.0:8000"]


Designed by BootstrapMade and modified by DoriDoro