Debug Mode: Django Docker Pycharm

digitalblkhippy

Valerie Phoenix ✊🏾

Posted on September 7, 2024

Debug Mode: Django Docker Pycharm

Getting your local setup to debug the code you're writing properly takes more time than any dev would like to admit. And let's not forget this is mostly a one-and-done setup, so if we don't write it down, we won't remember. This post is here to solve that exact issue! Let this serve as a written reminder of how to get your local dev environment up and running.

Prerequisites:

  • PyCharm Professional (for Docker support)
  • Docker and Docker Compose
  • Django REST Framework (DRF) Application

This post will not cover details about the Django, Docker, or Docker composer setup outside of the updates needed for debug mode. It assumes you already have a working knowledge of how to get that part to work.

Step 1: Dockerfile Setup for Debugging

Set up your Dockerfile to run in dev mode and allow connections from the PyCharm debugger.

Below is an example Dockerfile:

# Builder stage
FROM python:3.9-slim as builder

RUN chmod 1777 /tmp

# Install system dependencies
RUN apt-get update && apt-get install -y \
    libpq-dev \
    build-essential

WORKDIR /app

# Copy the requirements file into the container
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt > pip_install.log

# Copy the current directory contents into the container
COPY . /app

# Collect static files
RUN python manage.py collectstatic --noinput

# Final stage
FROM python:3.9-slim

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV DJANGO_SETTINGS_MODULE=template.settings.development

# Set work directory
WORKDIR /app

# Copy files from the builder stage
COPY --from=builder /app /app

# Install pydevd-pycharm for remote debugging and gunicorn for serving
RUN pip install gunicorn pydevd-pycharm==241.17890.14 psycopg2-binary

# Expose necessary ports
EXPOSE 8000 5679  # Web app port and debug port

# Entry point for the container
ENTRYPOINT ["sh", "-c", "python manage.py runserver 0.0.0.0:8000"]

Enter fullscreen mode Exit fullscreen mode

Things to keep in mind about this code

  • 241.17890.14 in pydevd-pycharm==241.17890.14 is going to be different depending on the version of Pycharm you have
  • We're exposing both 8000 (the web server port) and 5679 (the debugger port) for external access.

Step 2: Docker Compose Configuration

Let's get our docker-compose.yml file going to configure the web service (Django app) along with the database and other services.

Here is a sample docker-compose.yml:

version: '3'

services:
  web:
    environment:
      - DJANGO_ENVIRONMENT=development
      - DB_HOST=host.docker.internal
    build:
      context: .
    command: >
      sh -c "python manage.py migrate &&
             python manage.py collectstatic --noinput &&
             python manage.py runserver 0.0.0.0:8000"
    volumes:
      - .:/app
    ports:
      - "8000:8000"   # Expose web port
      - "5679:5679"   # Expose debugger port
    extra_hosts:
      - "host.docker.internal:host-gateway"
  db:
    image: postgres:13
    environment:
      - POSTGRES_DB=${DB_NAME}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}

Enter fullscreen mode Exit fullscreen mode

Let's jump into the code breakdown

  • We're mapping port 8000 for the web server and port 5679 for the PyCharm debugger.
  • extra_hosts ensures your Docker container can communicate with the host machine using host.docker.internal.

Step 3: Configure PyCharm for Debugging

  1. Create a Python Debug Server Configuration:
  2. In PyCharm navigate to Run ➡️ Edit Configurations.
  3. Click the + button and select Python Debug Server.
  4. Set the Host to 0.0.0.0 or your local machine’s IP address.
  5. Set the Port to 5679 (or the one you expose in your Docker setup).
  6. And hit Save!

  7. Start the Debugger Server:
    Start the PyCharm debugger by clicking the Debug button (green bug icon). This will start listening on the port we set.

Step 4: Add Remote Debugging Code to Django

In your Django project, you'll need to add the following code in your manage.py or wsgi.py to connect to the PyCharm debugger:

import pydevd_pycharm

# Connect to the PyCharm debug server
pydevd_pycharm.settrace('host.docker.internal', port=5679, stdoutToServer=True, stderrToServer=True, suspend=False)

Enter fullscreen mode Exit fullscreen mode

This snippet tells your Django app to connect back to the PyCharm debugger running on your host machine. host.docker.internal resolves to the host machine in Docker, and port=5679 matches the one we exposed earlier.

Step 5: Run Docker and Debug

  1. Build and Run Docker: Run the following command to start your containers:
docker-compose up --build
Enter fullscreen mode Exit fullscreen mode

This will build the Docker image and start the services, including Django running in development mode.

2. Set Breakpoints:
Set breakpoints in your Django code within PyCharm. The breakpoints should work because your container will connect to the PyCharm debug server running on port 5679.

3. Trigger Your Code:
Now, trigger any HTTP request in your Django REST Framework API. When the code hits the breakpoint, PyCharm will pause execution, allowing you to inspect the current state and step through the code.

Step 6: Troubleshooting

If you encounter the error bind: address already in use while running Docker, another process already uses port 5679. In this case, you can:

  • Stop the PyCharm debugger and restart Docker.
  • Change the port in your docker-compose.yml and PyCharm configuration to avoid conflicts.

Conclusion

This is the setup I use to run my Django REST Framework application in development mode inside a Docker container using PyCharm’s powerful debugger. This setup helps me debug my backend code by stepping through the code line by line, all locally.

By setting up your Docker container to communicate with PyCharm, you simplify writing, testing, and debugging your Django application, making it easier to write code!

Have fun breaking your code!

💖 💪 🙅 🚩
digitalblkhippy
Valerie Phoenix ✊🏾

Posted on September 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Debug Mode: Django Docker Pycharm
python Debug Mode: Django Docker Pycharm

September 7, 2024