I'm working on a Django/Postgres project and currently trying to dockerize. Postgresql has always worked fine on my pc, but now I'm having trouble spinning it up on docker. I get this error:
web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
I've tried a lot of solutions suggested online, but none have solved my problem.
.yml file
version: '3.8'
services:
web:
build:
context: ./web
network: host
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./web/:/usr/src/web/
ports:
- 8000:8000
env_file:
- ./.env.dev
depends_on:
- web_db
web_db:
image: postgres:12.5-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- POSTGRES_USER=username
- POSTGRES_PASSWORD=password
- POSTGRES_DB=db_name
volumes:
postgres_data:
env file
SECRET_KEY=secret
DEBUG=1
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
SQL_ENGINE=django.db.backends.postgresql_psycopg2
SQL_DATABASE=db_name
SQL_USER=username
SQL_PASSWORD=password
SQL_HOST=localhost
SQL_PORT=5432
settings.py
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql_psycopg2"),
"NAME": os.environ.get("SQL_DATABASE", "db_name"),
"USER": os.environ.get("SQL_USER", "username"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", ""),
}
}
sudo nano /var/lib/docker/volumes/project_postgres_data/_data/pg_hba.conf
#TYPE DATABASE USER ADDRESS METHOD
local all all trust
#IPv4 local connections:
host all all 127.0.0.1/32 trust
#IPv6 local connections:
host all all ::1/128 trust
local replication all trust
host replication all 127.0.0.1/32 trust
host replication all ::1/128 trust
host all all all md5
sudo nano /var/lib/docker/volumes/project_postgres_data/_data/postgresql.conf
listen_addresses = '*'
#port = 5432
All the configs seem to check out, so I have no idea why connection fails. Any ideas?
PS: I'll update the question with any extra info needed.
Use SQL_HOST=web_db
instead of SQL_HOST=localhost
in your env file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.