问题
I have a problem connecting my Postgres database to django project on docker container. I have already tried every solution found on the internet and nothing seems to work. I've already added host all all all md5 to my pg_hba.conf file, listen_addresses = '*' to postgresql.conf. Here is log from lsof -i :5432:
postgres 19774 postgres 5u IPv4 2046377 0t0 TCP *:postgresql (LISTEN)
postgres 19774 postgres 6u IPv6 2046378 0t0 TCP *:postgresql (LISTEN)
I've tried to open 5432 port by using ufw allow 5432/tcp, it seems to be open.
My docker-compose.yml file:
version: '3.8'
services:
db:
image: postgres:12.0-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
build: .
container_name: db
volumes:
- postgres_data:/var/lib/postgresql/data/
networks:
- djangonetwork
ports:
- '5432'
web:
build:
context: .
dockerfile: Dockerfile
command: python manage.py runserver 127.0.0.1:8000
volumes:
- ./TwitterClone/:/usr/src/TwitterClone/
ports:
- 8000:8000
env_file:
- ./.env
depends_on:
- db
links:
- db:db
networks:
- djangonetwork
networks:
djangonetwork:
driver: bridge
volumes:
postgres_data:
settings.py:
try:
DATABASE_PASSWORD = os.environ.get('POSTGRES_PASSWORD')
DATABASE_USER = os.environ.get('POSTGRES_USER')
DATABASE_NAME = os.environ.get('POSTGRES_DB')
except:
print('Could not get environment variables')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': DATABASE_NAME,
'USER': DATABASE_USER,
'PASSWORD': DATABASE_PASSWORD,
'HOST': '127.0.0.1',
'PORT': 5432,
}
}
No matter what I try to do, I always end up getting that error:
django.db.utils.OperationalError: 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?
Thank you in advance for any help, anything could help. Just let me know if you need more information from me, I will gladly provide it.
EDIT: I have edited my docker-compose file by deleting all networks related lines. Now I don't get the previous error, but it seems to have a problem with my PostgreSQL server running on port 5432:
ERROR: for db Cannot start service db: driver failed programming external connectivity on endpoint db (a1ed9a70eddb931e5d2a26522cb95a2873e019029420f8b994146e6bebe5ce09): Error starting userland proxy: listen tcp 0.0.0.0:5432: bind: address already in use
来源:https://stackoverflow.com/questions/62729917/connecting-postgresql-db-to-django-project-using-docker