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"]
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}
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
- Create a Python Debug Server Configuration:
- In PyCharm navigate to Run ➡️ Edit Configurations.
- Click the + button and select Python Debug Server.
- Set the Host to 0.0.0.0 or your local machine’s IP address.
- Set the Port to 5679 (or the one you expose in your Docker setup).
And hit Save!
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)
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
- Build and Run Docker: Run the following command to start your containers:
docker-compose up --build
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!
The above is the detailed content of Debug Mode: Django Docker Pycharm. For more information, please follow other related articles on the PHP Chinese website!

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.