skip to Main Content

I have made a Django project with a postgresql backend and am trying to containerize it.
This is my Dockerfile:

FROM python:3.9

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /app

COPY requirements.txt /app/

RUN pip install --no-cache-dir -r requirements.txt

COPY . /app/

EXPOSE 8000

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

This is my docker-compose.yml file:

version: '3'

services:
  web:
    build: .
    ports:
      - "8000:8000"
    depends_on:
      - db
    networks:
      - inventory_network

  db:
    ports: 
      - "5433:5432"
    image: postgres:16
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=root
      - POSTGRES_DB=InventoryManagement
    networks:
      - inventory_network

networks:
  inventory_network:
    driver: bridge

This is my settings.py within the django project to connect to the db:

WSGI_APPLICATION = 'Inventory_management.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'InventoryManagement',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': 'db', 
        'PORT': '5433'
    }
}

The sudo docker build . command runs without any errors.
The error I get when I try to run 'sudo docker compose up' is as follows:
Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432?

I have confirmed that the postgres server is running:
Server active(running)
This application also runs without any errors on my local.

I had created a network(inventory_network) on which I tried attaching my containers. But one thing I noticed was that whenever I ran the ‘compose up’ command, it created another network inventory_management_inventory_network automatically to which the containers attached instead of my specified network inventory_network:

This is what I got when i ran ‘inspect’ on both these networks, as I wasn’t sure if this was related to the issue:
inventory_network inspect
inventory_management_inventory_network inspect

This is the complete error message:
sudo docker compose up

WARN[0000] /home/prisha/Inventory_Management/docker-compose.yml: `version` is obsolete                                                                                                                     
[+] Running 1/5
 ✔ Network inventory_management_default    Created                                                                                                                                                    0.3s 
 ⠋ Container rabbitmq-container            Created                                                                                                                                                    2.0s 
 ⠋ Container inventory_management-adminer  Created                                                                                                                                                    2.0s 
 ⠋ Container inventory_management-db-1     Created                                                                                                                                                    2.0s 
 ⠦ Container inventory_management-web-1    Created                                                                                                                                                    0.7s 
Attaching to inventory_management-adminer, db-1, web-1, rabbitmq-container
inventory_management-adminer  | [Tue Apr 16 17:16:29 2024] PHP 7.4.33 Development Server (http://[::]:8080) started
db-1                          | The files belonging to this database system will be owned by user "postgres".
db-1                          | This user must also own the server process.
db-1                          | 
db-1                          | The database cluster will be initialized with locale "en_US.utf8".
db-1                          | The default database encoding has accordingly been set to "UTF8".
db-1                          | The default text search configuration will be set to "english".
db-1                          | 
db-1                          | Data page checksums are disabled.
db-1                          | 
db-1                          | fixing permissions on existing directory /var/lib/postgresql/data ... ok
db-1                          | creating subdirectories ... ok
db-1                          | selecting dynamic shared memory implementation ... posix
db-1                          | selecting default max_connections ... 100
db-1                          | selecting default shared_buffers ... 128MB
db-1                          | selecting default time zone ... Etc/UTC
db-1                          | creating configuration files ... ok
db-1                          | running bootstrap script ... ok
db-1                          | performing post-bootstrap initialization ... ok
db-1                          | syncing data to disk ... ok
db-1                          | 
db-1                          | 
db-1                          | Success. You can now start the database server using:
db-1                          | 
db-1                          |     pg_ctl -D /var/lib/postgresql/data -l logfile start
db-1                          | 
db-1                          | initdb: warning: enabling "trust" authentication for local connections
db-1                          | initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.
db-1                          | waiting for server to start....2024-04-16 17:16:48.579 UTC [49] LOG:  starting PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
db-1                          | 2024-04-16 17:16:48.585 UTC [49] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db-1                          | 2024-04-16 17:16:48.631 UTC [52] LOG:  database system was shut down at 2024-04-16 17:16:34 UTC
db-1                          | 2024-04-16 17:16:48.648 UTC [49] LOG:  database system is ready to accept connections
db-1                          |  done
db-1                          | server started
db-1                          | 
db-1                          | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
db-1                          | 
db-1                          | 2024-04-16 17:16:50.516 UTC [49] LOG:  received fast shutdown request
db-1                          | waiting for server to shut down....2024-04-16 17:16:50.625 UTC [49] LOG:  aborting any active transactions
db-1                          | 2024-04-16 17:16:50.632 UTC [49] LOG:  background worker "logical replication launcher" (PID 55) exited with exit code 1
db-1                          | 2024-04-16 17:16:50.635 UTC [50] LOG:  shutting down
db-1                          | 2024-04-16 17:16:50.656 UTC [50] LOG:  checkpoint starting: shutdown immediate
db-1                          | 2024-04-16 17:16:50.689 UTC [50] LOG:  checkpoint complete: wrote 3 buffers (0.0%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0.008 s, sync=0.011 s, total=0.055 s; sync files=2, longest=0.007 s, average=0.006 s; distance=0 kB, estimate=0 kB; lsn=0/14EAA70, redo lsn=0/14EAA70
db-1                          | 2024-04-16 17:16:50.696 UTC [49] LOG:  database system is shut down
db-1                          |  done
db-1                          | server stopped
db-1                          | 
db-1                          | PostgreSQL init process complete; ready for start up.
db-1                          | 
db-1                          | 2024-04-16 17:16:50.946 UTC [1] LOG:  starting PostgreSQL 16.2 (Debian 16.2-1.pgdg120+2) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
db-1                          | 2024-04-16 17:16:50.947 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db-1                          | 2024-04-16 17:16:50.947 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db-1                          | 2024-04-16 17:16:50.980 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db-1                          | 2024-04-16 17:16:51.051 UTC [63] LOG:  database system was shut down at 2024-04-16 17:16:50 UTC
db-1                          | 2024-04-16 17:16:51.074 UTC [1] LOG:  database system is ready to accept connections
web-1                         | Watching for file changes with StatReloader
web-1                         | Exception in thread django-main-thread:
web-1                         | Traceback (most recent call last):
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
web-1                         |     self.connect()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect
web-1                         |     self.connection = self.get_new_connection(conn_params)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
web-1                         |     connection = Database.connect(**conn_params)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
web-1                         |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
web-1                         | psycopg2.OperationalError: could not connect to server: Connection refused
web-1                         |         Is the server running on host "localhost" (127.0.0.1) and accepting
web-1                         |         TCP/IP connections on port 5432?
web-1                         | could not connect to server: Cannot assign requested address
web-1                         |         Is the server running on host "localhost" (::1) and accepting
web-1                         |         TCP/IP connections on port 5432?
web-1                         | 
web-1                         | 
web-1                         | The above exception was the direct cause of the following exception:
web-1                         | 
web-1                         | Traceback (most recent call last):
web-1                         |   File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner
web-1                         |     self.run()
web-1                         |   File "/usr/local/lib/python3.9/threading.py", line 917, in run
web-1                         |     self._target(*self._args, **self._kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
web-1                         |     fn(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
web-1                         |     autoreload.raise_last_exception()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
web-1                         |     raise _exception[1]
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute
web-1                         |     autoreload.check_errors(django.setup)()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
web-1                         |     fn(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
web-1                         |     apps.populate(settings.INSTALLED_APPS)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate
web-1                         |     app_config.import_models()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models
web-1                         |     self.models_module = import_module(models_module_name)
web-1                         |   File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
web-1                         |     return _bootstrap._gcd_import(name[level:], package, level)
web-1                         |   File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
web-1                         |   File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
web-1                         |   File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
web-1                         |   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
web-1                         |   File "<frozen importlib._bootstrap_external>", line 850, in exec_module
web-1                         |   File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
web-1                         |   File "/app/schema/models.py", line 17, in <module>
web-1                         |     Inventory.objects.create(**order_data)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
web-1                         |     return getattr(self.get_queryset(), name)(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 453, in create
web-1                         |     obj.save(force_insert=True, using=self.db)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 739, in save
web-1                         |     self.save_base(using=using, force_insert=force_insert,
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 776, in save_base
web-1                         |     updated = self._save_table(
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 881, in _save_table
web-1                         |     results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 919, in _do_insert
web-1                         |     return manager._insert(
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
web-1                         |     return getattr(self.get_queryset(), name)(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert
web-1                         |     return query.get_compiler(using=using).execute_sql(returning_fields)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1414, in execute_sql
web-1                         |     with self.connection.cursor() as cursor:
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor
web-1                         |     return self._cursor()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor
web-1                         |     self.ensure_connection()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
web-1                         |     self.connect()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
web-1                         |     raise dj_exc_value.with_traceback(traceback) from exc_value
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
web-1                         |     self.connect()
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect
web-1                         |     self.connection = self.get_new_connection(conn_params)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
web-1                         |     return func(*args, **kwargs)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
web-1                         |     connection = Database.connect(**conn_params)
web-1                         |   File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
web-1                         |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
web-1                         | django.db.utils.OperationalError: could not connect to server: Connection refused
web-1                         |         Is the server running on host "localhost" (127.0.0.1) and accepting
web-1                         |         TCP/IP connections on port 5432?
web-1                         | could not connect to server: Cannot assign requested address
web-1                         |         Is the server running on host "localhost" (::1) and accepting
web-1                         |         TCP/IP connections on port 5432?
web-1                         | 
rabbitmq-container            | 2024-04-16 17:16:56.701302+00:00 [notice] <0.44.0> Application syslog exited with reason: stopped
rabbitmq-container            | 2024-04-16 17:16:56.720113+00:00 [notice] <0.248.0> Logging: switching to configured handler(s); following messages may not be visible in this log output
rabbitmq-container            | 2024-04-16 17:16:56.721332+00:00 [notice] <0.248.0> Logging: configured log handlers are now ACTIVE
rabbitmq-container            | 2024-04-16 17:16:56.778579+00:00 [info] <0.248.0> ra: starting system quorum_queues
rabbitmq-container            | 2024-04-16 17:16:56.778737+00:00 [info] <0.248.0> starting Ra system: quorum_queues in directory: /var/lib/rabbitmq/mnesia/rabbit@4777f5259953/quorum/rabbit@4777f5259953
rabbitmq-container            | 2024-04-16 17:16:56.896967+00:00 [info] <0.262.0> ra system 'quorum_queues' running pre init for 0 registered servers
rabbitmq-container            | 2024-04-16 17:16:56.945305+00:00 [info] <0.263.0> ra: meta data store initialised for system quorum_queues. 0 record(s) recovered
rabbitmq-container            | 2024-04-16 17:16:56.957634+00:00 [notice] <0.268.0> WAL: ra_log_wal init, open tbls: ra_log_open_mem_tables, closed tbls: ra_log_closed_mem_tables
rabbitmq-container            | 2024-04-16 17:16:56.968432+00:00 [info] <0.248.0> ra: starting system coordination
rabbitmq-container            | 2024-04-16 17:16:56.968511+00:00 [info] <0.248.0> starting Ra system: coordination in directory: /var/lib/rabbitmq/mnesia/rabbit@4777f5259953/coordination/rabbit@4777f5259953
rabbitmq-container            | 2024-04-16 17:16:56.969487+00:00 [info] <0.275.0> ra system 'coordination' running pre init for 0 registered servers
rabbitmq-container            | 2024-04-16 17:16:56.970048+00:00 [info] <0.276.0> ra: meta data store initialised for system coordination. 0 record(s) recovered
rabbitmq-container            | 2024-04-16 17:16:56.970225+00:00 [notice] <0.281.0> WAL: ra_coordination_log_wal init, open tbls: ra_coordination_log_open_mem_tables, closed tbls: ra_coordination_log_closed_mem_tables
rabbitmq-container            | 2024-04-16 17:16:56.977368+00:00 [info] <0.248.0> ra: starting system coordination
rabbitmq-container            | 2024-04-16 17:16:56.977434+00:00 [info] <0.248.0> starting Ra system: coordination in directory: /var/lib/rabbitmq/mnesia/rabbit@4777f5259953/coordination/rabbit@4777f5259953
rabbitmq-container            | 2024-04-16 17:16:57.172023+00:00 [info] <0.248.0> Waiting for Khepri leader for 30000 ms, 9 retries left
rabbitmq-container            | 2024-04-16 17:16:57.225862+00:00 [notice] <0.284.0> RabbitMQ metadata store: candidate -> leader in term: 1 machine version: 0
rabbitmq-container            | 2024-04-16 17:16:57.247313+00:00 [info] <0.248.0> Khepri leader elected
rabbitmq-container            | 2024-04-16 17:16:57.868397+00:00 [info] <0.248.0> 
rabbitmq-container            | 2024-04-16 17:16:57.868397+00:00 [info] <0.248.0>  Starting RabbitMQ 3.13.1 on Erlang 26.2.2 [jit]
rabbitmq-container            | 2024-04-16 17:16:57.868397+00:00 [info] <0.248.0>  Copyright (c) 2007-2024 Broadcom Inc and/or its subsidiaries
rabbitmq-container            | 2024-04-16 17:16:57.868397+00:00 [info] <0.248.0>  Licensed under the MPL 2.0. Website: https://rabbitmq.com
rabbitmq-container            | 
rabbitmq-container            |   ##  ##      RabbitMQ 3.13.1
rabbitmq-container            |   ##  ##
rabbitmq-container            |   ##########  Copyright (c) 2007-2024 Broadcom Inc and/or its subsidiaries
rabbitmq-container            |   ######  ##
rabbitmq-container            |   ##########  Licensed under the MPL 2.0. Website: https://rabbitmq.com
rabbitmq-container            | 
rabbitmq-container            |   Erlang:      26.2.2 [jit]
rabbitmq-container            |   TLS Library: OpenSSL - OpenSSL 3.1.5 30 Jan 2024
rabbitmq-container            |   Release series support status: supported
rabbitmq-container            | 
rabbitmq-container            |   Doc guides:  https://www.rabbitmq.com/docs/documentation
rabbitmq-container            |   Support:     https://www.rabbitmq.com/docs/contact
rabbitmq-container            |   Tutorials:   https://www.rabbitmq.com/tutorials
rabbitmq-container            |   Monitoring:  https://www.rabbitmq.com/docs/monitoring
rabbitmq-container            | 
rabbitmq-container            |   Logs: <stdout>
rabbitmq-container            | 
rabbitmq-container            |   Config file(s): /etc/rabbitmq/conf.d/10-defaults.conf
rabbitmq-container            |                   /etc/rabbitmq/conf.d/20-management_agent.disable_metrics_collector.conf
rabbitmq-container            | 
rabbitmq-container            |   Starting broker...2024-04-16 17:16:57.869626+00:00 [info] <0.248.0> 

I have tried everything I know and would really appreciate any inputs.

2

Answers


  1. It’d be helpful to know what your project layout looks like. Is it something like this?

    ├── docker-compose.yml
    ├── Dockerfile
    ├── Inventory_management
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py
    └── requirements.txt
    

    Can you please add this information to your question?

    Also, for the setup you describe you should be using port 5432 (not 5433) in your settings.py:

    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.postgresql",
            "NAME": "InventoryManagement",
            "USER": "postgres",
            "PASSWORD": "root",
            "HOST": "db",
            "PORT": "5432",
        }
    }
    

    As noted in one of the comments, port mappings don’t apply to connections between containers.

    Login or Signup to reply.
  2. In the error log, there is a line as "WARN[0000] /home/prisha/Inventory_Management/docker-compose.yml: version is obsolete":

    docker-compose.yml: version is obsolete"

    As Docker has made this version line obsolete, remove this line from the docker-compose.yml file which is most probably causing this problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search