docker-library / docker

Docker Official Image packaging for Docker
Apache License 2.0
1.09k stars 568 forks source link

Docker and psycopg2: Cannot assign requested address to server at "localhost" #494

Closed brunolnetto closed 1 month ago

brunolnetto commented 1 month ago

I try to connect to a database using python library psycopg2. Here is the library I use: https://github.com/brunolnetto/psycopg-operational-error. The steps to reproduce are:

  1. Install dependencies: pip install -r requirements.txt;
  2. Host the database: docker compose up -d
  3. Run script: python3 main.py

docker-compose.yml

version: '3.9'

services:
  postgres:
    image: postgres:latest
    restart: always
    env_file: .env
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

main.py

from psycopg2 import connect

from os import getenv

DB_USER = getenv('POSTGRES_USER')
DB_PASS = getenv('POSTGRES_PASSWORD')
DB_HOST = getenv('POSTGRES_HOST', 'localhost')
DB_PORT = getenv('POSTGRES_PORT', '5432')
DB_NAME = getenv('POSTGRES_NAME')

try:
    conn = connect(
        database=DB_NAME,
        user=DB_USER,
        password=DB_PASS,
        host=DB_HOST,
        port=DB_PORT
    )
    print("Database connected successfully")
except Exception as e:
    print(f"Database not connected successfully: {e}")
whalelines commented 1 month ago

This repository contains the source for the docker Docker Official Image, https://hub.docker.com/_/docker, and is not a general resource for running Docker containers.

You can ask for help in the Docker Community Slack. If you are not already a member of the Docker Community Slack, you can use this link to join. You can find more support options at Docker Support, including documentation for Docker Compose.

When you do ask for help, I would recommend including what errors are being reported. Good luck!