View.py request error: Failed to establish a new connection: [Errno 111] Connection refused

I setup docker for my 2 django project (frontend | backend)

this is my yaml

`version: "3.12"

services:
  mysql:
    image: mysql:8.0
    container_name: mysql_db
    restart: always
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
      MYSQL_DATABASE: gfmic_frontend_db_v1
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql
    networks:
      - backend

  event_backend:
    build: ./GFMIC_Backend
    container_name: GFMIC_Backend
    depends_on:
      - mysql
    volumes:
      - ./GFMIC_Backend:/django
    ports:
      - "8001:8001"
    expose:
      - 8001
    environment:
      - DJANGO_SETTINGS_MODULE=GFMIC_Backend.settings
      - DB_HOST=mysql  # Service name for MySQL container
      - DB_NAME=gfmic_backend_db_v1
      - DB_USER=root
      - DB_PASSWORD=  # Empty password
      - SECRET_KEY=SECRET
      - DEBUG=True
      - ALLOWED_HOSTS=127.0.0.1 event_backend event_frontend localhost 0.0.0.0 host.docker.internal
    networks:
      - backend

  event_frontend:
    build: ./GFMIC_Frontend
    container_name: GFMIC_Frontend
    depends_on:
      - mysql
    ports:
      - "8000:8000"
    expose:
      - 8000
    volumes:
      - ./GFMIC_Frontend:/django
    environment:
      - DJANGO_SETTINGS_MODULE=GFMIC_Frontend.settings
      - DB_HOST=mysql  # Service name for MySQL container
      - DB_NAME=gfmic_frontend_db_v1
      - DB_USER=root
      - DB_PASSWORD=  # Empty password
      - SECRET_KEY=SECRET
      - DEBUG=True
      - ALLOWED_HOSTS=127.0.0.1 event_backend event_frontend localhost 0.0.0.0 host.docker.internal
    networks:
      - backend

volumes:
  mysql_data:

networks:
  backend:
    driver: bridge
`

I got the error

"Error fetching events: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /Event_Management/api/EventsDetails/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f85a023b710>: Failed to establish a new connection: [Errno 111] Connection refused'))"

when I try to api request to my views.py

example:

`def events_list(request):
    title= "Events List"
    api_url = 'http://127.0.0.1:8001/Event_Management/api/EventsDetails/'  # Replace with your API endpoint

    try:
        response = requests.get(api_url)
        response.raise_for_status()  # Raises an HTTPError for bad responses (4xx and 5xx)
        events = response.json()  # Parse the JSON response
    except requests.exceptions.RequestException as e:
        # Handle request exceptions (e.g., network errors)
        events = []
        # Optionally log the error or provide feedback to the user
        print(f"Error fetching events: {e}")

    return render(request, 'events/events_list.html', {'events': events, 'title': title})`

I also try the http://event_backend:8001/Event_Management/api/EventsDetails/

It shows:

django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'event_backend:8001'. The domain name provided is not valid according to RFC 1034/1035.

but in javascript thru ajax it works:

`$.ajax({
        url: 'http://127.0.0.1:8001/Event_Management/api/EventsDetails/',
        method: 'GET',
        success: function(response) {
            console.log('Response:', response);
            // Clear the existing table data
            event_table.clear();

            // Process the response data
            response.forEach(function(event) {
                // Add data to DataTable
                event_table.row.add([event.title,
                    event.venue,
                    event.from_date + ' to ' + event.to_date,
                    event.from_time + ' - ' + event.to_time,
                    `<span class="badge badge-light-${getBadgeClass(event.type)}">${event.type}</span>`,
                    event.registration_fee,
                    `<button type="button" class="btn btn-outline btn-outline-primary btn-active-primary dropdown-toggle"
                        data-bs-toggle="dropdown" aria-expanded="false">
                        Menu
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kt_modal_edit_event">
                            <i class="bi bi-pencil-square text-primary fs-6 me-2"></i>Edit Event Details
                        </a></li>
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kt_modal_view_event">
                            <i class="bi bi-calendar-event text-info fs-6 me-2"></i>View Event Details
                        </a></li>
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kt_modal_add_topic_speaker">
                            <i class="bi bi-plus-circle text-success fs-6 me-2"></i>Add Topic & Speaker
                        </a></li>
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kt_modal_view_topic_speaker">
                            <i class="bi bi-eye text-info fs-6 me-2"></i>View Topic & Speaker
                        </a></li>
                        <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#kt_modal_generate_qr">
                            <i class="bi bi-qr-code text-dark fs-6 me-2"></i>Generate QR
                        </a></li>
                        <li><a class="dropdown-item" href="{% url 'events_attendees' %}">
                            <i class="bi bi-people text-warning fs-6 me-2"></i>Event Attendees
                        </a></li>
                        <li><a class="dropdown-item" id="#" class="archiveBtn">
                            <i class="bi bi-archive fs-6 me-2" style="color: #343a40;"></i>Archive
                        </a></li>
                    </ul>`
                ]).draw();
            });
        },
        error: function(xhr, status, error) {
            console.error('Error fetching data:', {
                status: status,
                error: error,
                responseText: xhr.responseText
            });
            // Display a user-friendly error message if needed
            Swal.fire({
                title: 'Error!',
                text: 'There was an error fetching event details.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    });`

Hope to solve this problem

SOLVED:

JUST DON'T USE UNDERSCORE IN APP NAME IN DOCKER USE "eventbackend" INSTEAD OF "event_backend"

FOR THE F "_" 3 hours of debugging

Back to Top