How to fix "Can't connect" error? Django app container fails connecting to MySQL

47 Views Asked by At

I have a Django application which is running in a container. I was trying to connect to MySQL-database running on my local machine..

In the settings.py of Django project, I using db_host to IP address my local machine for database configuration. In container I tried to curl my local machine IP address and it worked fine.

Even then my Django app gives the error:

Can't connect to server on <ip_address>..

My Dockerfile.

# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set environment variables for Python
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set the working directory in the container
WORKDIR /app

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

# Install system dependencies for mysqlclient
RUN apt-get update \
    && apt-get install -y python3-dev default-libmysqlclient-dev build-essential pkg-config gcc curl \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
RUN pip install --upgrade pip \
    && pip install -r requirements.txt

# Expose port 8000 to allow communication to/from server
EXPOSE 8000

# Run the Django development server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

What am I doing wrong?

0

There are 0 best solutions below