veryacademy/django-ecommerce-project-v2

could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

Closed this issue · 4 comments

Hello, i have this issue when I try to connect elasticsearch with postgres vie docker. This error pop up when I rebuild the container after adding elasticseasrch to docker-compose which is this:

version: '3.8'

services:
  web:
    build: .
    command: gunicorn config.wsgi -b 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      # - db
      - pgdb_ecommerce
      - search
    environment:
      - "DJANGO_SECRET_KEY=t8wrj!=x&em6+x%z1_!m6n8m3$$jis8!wkhxzn##!_(-%-u9t2t"
      - "DJANGO_DEBUG=True"
      - "DJANGO_SECURE_SSL_REDIRECT=False"
      - "DJANGO_SECURE_HSTS_SECONDS=0"
      - "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False"
      - "DJANGO_SECURE_HSTS_PRELOAD=False"
      - "DJANGO_SESSION_COOKIE_SECURE=False"
      - "DJANGO_CSRF_COOKIE_SECURE=False"
      - USE_S3=false

  # db:
  #   image: postgres:11
  #   volumes:
  #     - postgres_data:/var/lib/postgresql/data/
  #   environment:
  #     - "POSTGRES_HOST_AUTH_METHOD=trust"

  pgdb:
    container_name: pgdb_ecommerce
    image: postgres
    restart: always
    ports:
      - 5432:5432
    environment:
      - POSTGRES_DB=ecommerce
      - POSTGRES_USER=ecommerce
      - POSTGRES_PASSWORD=password

  esearch:
    container_name: search
    image: elasticsearch:7.14.2
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"

volumes:
  postgres_data:

I used to run a db before,but after running
docker-compose exec web python manage.py search_index --build
I got this error

elasticsearch.exceptions.ConnectionError:
ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused) caused by:
NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused)

which is I guess the same issue, bc can't connect them right?
so I change the db to pgdb as yours to see where is the problem but got the same error again
these are my files I guess you need to see

ecommmerce.search.views.py

from django.http import HttpResponse
from elasticsearch_dsl import Q
from rest_framework.views import APIView
from rest_framework.pagination import LimitOffsetPagination

from search.documents import ProductInventoryDocument

from drf.serializer import ProductInventorySerializer

# Create your views here.


class SearchProductInventory(APIView, LimitOffsetPagination):
    productinventory_serializer = ProductInventorySerializer
    search_document = ProductInventoryDocument

    def get(self, request, query):
        try:
            q = Q(
                "multi_match",
                query=query,
                fields=[
                    "sku",
                ],
            )
            search = self.search_document.search().query(q)
            response = search.execute()

            results = self.paginate_queryset(response, request, view=self)
            serializer = self.productinventory_serializer(results, many=True)
            return self.get_paginated_response(serializer.data)

        except Exception as e:
            return HttpResponse(e, status=500)

ecommerce.search.documents.py

from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
from inventory.models import ProductInventory, Product


@registry.register_document
class ProductInventoryDocument(Document):

    product = fields.ObjectField(properties={"name": fields.TextField()})

    class Index:
        name = "productinventory"

    class Django:
        model = ProductInventory

        fields = [
            "id",
            "sku",
            "store_price",
            "is_default",
        ]

ecommece.urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from search.views import SearchProductInventory
from drf.views import *

router = routers.DefaultRouter()
router.register(
    r"api",
    AllProductsViewSet,
    basename="allproducts",
)
router.register(
    r"product/(?P<slug>[^/.]+)",
    ProductByCategory,
    basename="Products",
)

urlpatterns = [
    # Djago admin
    path("bingo/", admin.site.urls),
    # User management
    path("accounts/", include("allauth.urls")),
    # Local apps
    path("", include("dashboard.urls")),
    path("books/", include("books.urls")),
    path("order/", include("order.urls")),
    path("checkout/", include("checkout.urls")),
    path("api_home/", include(router.urls)),
    path("search/<str:query>", SearchProductInventory.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = [
        path("__debug__", include(debug_toolbar.urls)),
    ] + urlpatterns

i add these lines to my settings

INSTALLED_APPS = [
    ....
    ....
    'django_elasticsearch_dsl',
    'rest_framework',
    'inventory',
    'drf',
    'search',
    'demo',
    'dashboard',
    # all the other apps you added to, from the previous parts

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": "ecommerce", #I made this database with this user and pass and can find it with pgadmin and it works fine with load-fixtures command
        "USER": "ecommerce",
        "PASSWORD": "password",
        "HOST": "127.0.0.1",
        "PORT": "5432",
    }
}


REST_FRAMEWORK = {
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
    "PAGE_SIZE": 10,
}

ELASTICSEARCH_DSL = {
    "default": {"hosts": "localhost:9200"},
}

I guess these are some extra info maybe it helps
now I'm at part 6 from this tuts,
and when I run this command
curl -X GET localhost:9200/_cluster/health
it works fine

{"cluster_name":"docker-cluster","status":"green","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"active_primary_shards":1,"active_shards":1,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":100.0}

if you need any more info about my other files , just asked , thanks in advance .

Hey. The problem here is in the settings file I think.

ELASTICSEARCH_DSL = {
"default": {"hosts": "localhost:9200"},
}

Because you are running django in a container you need to change this setting to find the container.

ELASTICSEARCH_DSL = {
"default": {"hosts": "search"}, # in this case I use the name of your service
}

and also again the same issue with your database connection in the settings file

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "ecommerce", #I made this database with this user and pass and can find it with pgadmin and it works fine with load-fixtures command
"USER": "ecommerce",
"PASSWORD": "password",
"HOST": "pgdb_ecommerce", # changed this line to find the pgdb container
"PORT": "5432",
}
}

Have you built the index and named it correctly - search_index --build

thanks a lot it works as it should be , so i deleted the new comment(but you was faster than me delete action lol)
again thanks in advance,
so going back to continue the tut :)

Thank you