Skip to content

Instantly share code, notes, and snippets.

@ajeetraina
Created November 25, 2024 17:11
Show Gist options
  • Save ajeetraina/a870fd6bd7d170dde53a06a8a66e259c to your computer and use it in GitHub Desktop.
Save ajeetraina/a870fd6bd7d170dde53a06a8a66e259c to your computer and use it in GitHub Desktop.
# Use the official Python runtime image
FROM python:3.13
# Create the app directory
RUN mkdir /app
# Set the working directory inside the container
WORKDIR /app
# Set environment variables
# Prevents Python from writing pyc files to disk
ENV PYTHONDONTWRITEBYTECODE=1
#Prevents Python from buffering stdout and stderr
ENV PYTHONUNBUFFERED=1
# Upgrade pip
RUN pip install --upgrade pip
# Copy the Django project and install dependencies
COPY . /app/
# run this command to install all dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the Django project to the container
COPY . /app/
# Expose the Django port
EXPOSE 8000
# Run Django’s development server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
```
@ajeetraina
Copy link
Author

``dockerfile

Stage 1: Base build stage

FROM python:3.13-slim AS builder

Create the app directory

RUN mkdir /app

Set the working directory

WORKDIR /app

Set environment variables to optimize Python

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

Upgrade pip and install dependencies

RUN pip install --upgrade pip

Copy the requirements file first (better caching)

COPY requirements.txt /app/

Install Python dependencies

RUN pip install --no-cache-dir -r requirements.txt

Stage 2: Production stage

FROM python:3.13-slim

RUN useradd -m -r appuser &&
mkdir /app &&
chown -R appuser /app

Copy the Python dependencies from the builder stage

COPY --from=builder /usr/local/lib/python3.13/site-packages/ /usr/local/lib/python3.13/site-packages/
COPY --from=builder /usr/local/bin/ /usr/local/bin/

Set the working directory

WORKDIR /app

Copy application code

COPY --chown=appuser:appuser . .

Set environment variables to optimize Python

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

Switch to non-root user

USER appuser

Expose the application port

EXPOSE 8000

Start the application using Gunicorn

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "my_docker_django_app.wsgi:application"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment