'Why I can't connect to postgres db from docker container? [duplicate]
My docker-compose.yml:
version: "3.9"
services:
db:
container_name: "db_container"
image: postgres:14-alpine
restart: unless-stopped
shm_size: 5g
env_file:
- ./postgres.env
volumes:
- postgres_data:/var/lib/postgresql/postgres_data
new_app:
container_name: "new_app"
build:
context: .
ports:
- '8080:8080'
volumes:
- .:/new_app
env_file:
- .env
depends_on: [db]
volumes:
postgres_data:
When I try to add data in my table, I receive this error:
sqlalchemy.exc.OperationalError: (psycopg2.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? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
Help me please solve my problem.
Solution 1:[1]
From the looks of the error, it looks like your app is assuming the database is running on the same host (i.e. the same container), given it's trying to connect to localhost. Each container in the network that Docker creates is given a hostname corresponding to the service name, so your database will be accessible with a hostname of db. See this for further information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ndc85430 |
