1
resposta

[Dúvida] "psycopg2.OperationalError: connection to server at '172.27.0.2', port 5432 failed: Connection timed out (0x0000274C/10060)"

Insira aqui a descrição dessa imagem para ajudar na acessibilidade Este é o ip do meu container Postgresql, estou conseguindo dar um GET no postman utilizando este ip, mas ao criar testes unitários e utilizar mock para simular, está dando timeout. Ao trocar o host para localhost consigo rodar os testes porém não consigo utilizar o Postman. Gostaria de saber alguma forma de fazer meu container python enxergar o ip do container Postgre. Eles estão na mesma network, ao entrar no terminal do meu container python consigo pingar o container postgre. Erro: ================================== FAILURES =================================== ______________________________ test_ListCategory ______________________________

def test_ListCategory():
  listCategory = ListCategory()

tests\UnitTests\Application\UseCases\Category\test_ListCategory.py:7:


src\Application\UseCases\Category\ListCategory.py:7: in init self.connection = psycopg2.connect(


dsn = 'user=postgres password=root host=172.27.0.2 port=5432 client_encoding=utf-8 dbname=Filmes' connection_factory = None, cursor_factory = None kwargs = {'client_encoding': 'utf-8', 'database': 'Filmes', 'host': '172.27.0.2', 'password': 'root', ...} kwasync = {}

def connect(dsn=None, connection_factory=None, cursor_factory=None, **kwargs):
    """
    Create a new database connection.

    The connection parameters can be specified as a string:

        conn = psycopg2.connect("dbname=test user=postgres password=secret")

    or using a set of keyword arguments:

        conn = psycopg2.connect(database="test", user="postgres", password="secret")

    Or as a mix of both. The basic connection parameters are:

    - *dbname*: the database name
    - *database*: the database name (only as keyword argument)
    - *user*: user name used to authenticate
    - *password*: password used to authenticate
    - *host*: database host address (defaults to UNIX socket if not provided)
    - *port*: connection port number (defaults to 5432 if not provided)

    Using the *connection_factory* parameter a different class or connections
    factory can be specified. It should be a callable object taking a dsn
    argument.

    Using the *cursor_factory* parameter, a new default cursor factory will be
    used by cursor().

    Using *async*=True an asynchronous connection will be created. *async_* is
    a valid alias (for Python versions where ``async`` is a keyword).

    Any other keyword parameter will be passed to the underlying client
    library: the list of supported parameters depends on the library version.

    """
    kwasync = {}
    if 'async' in kwargs:
        kwasync['async'] = kwargs.pop('async')
    if 'async_' in kwargs:
        kwasync['async_'] = kwargs.pop('async_')

    dsn = _ext.make_dsn(dsn, **kwargs)
  conn = _connect(dsn, connection_factory=connection_factory, **kwasync)

E psycopg2.OperationalError: connection to server at "172.27.0.2", port 5432 failed: Connection timed out (0x0000274C/10060) E Is the server running on that host and accepting TCP/IP connections?

venv\Lib\site-packages\psycopg2_init_.py:122: OperationalError =========================== short test summary info =========================== FAILED tests/UnitTests/Application/UseCases/Category/test_ListCategory.py::test_ListCategory ============================= 1 failed in 21.24s ============================== Finished running tests!

1 resposta

Oi, Fabio, tudo bem?

Como não tenho acesso ao seu projeto, é um pouco difícil dar uma solução específica. Vou deixar aqui algumas recomendações, e você vê se alguma funciona direitinho, tá bem?

  • Verificar as configurações de rede do Docker: garantir que a rede entre os containers está configurada da maneira certa. Você pode verificar isso com o comando docker network inspect [nome_da_rede]. Isso vai mostrar se ambos os containers estão realmente na mesma rede e se os IPs estão corretos.

  • Uso do nome do serviço Docker: em vez de usar o endereço IP direto do container PostgreSQL, tente usar o nome do serviço definido no Docker Compose (ou na configuração do Docker que você está usando). Por exemplo, se o seu serviço do Postgres é chamado db no Docker Compose, você deve usar:

    host='db'
    

Isso ajuda a resolver problemas de IP dinâmico que podem ocorrer quando os containers são reiniciados.

  • Configurações do PostgreSQL: verifique se o PostgreSQL está configurado para aceitar conexões do seu container Python. Você pode ver no arquivo postgresql.conf (verifique a linha listen_addresses) e pelo arquivo pg_hba.conf para garantir que as conexões estão sendo aceitas do IP ou rede correta.

  • Teste com ferramentas de rede: você pode usar ferramentas como o telnet ou nc para verificar se a porta 5432 está realmente aberta e acessível do seu container Python. Por exemplo:

    nc -zv 172.27.0.2 5432
    

    Ou se estiver usando o nome do serviço:

    nc -zv db 5432
    

Espero que isso te dê uma ajudinha! :)

Abraços!

Caso este post tenha lhe ajudado, por favor, marcar como solucionado ✓.