skip to Main Content

I have problem connecting to my Db that is running on a container on Docker using postres image:

docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres

My typescript code (is on a ts file)

app.get("/hello", async (request: Request, response: Response) => {
    const pool = new Pool({
        user: 'admin',
        host: 'localhost',
        database: 'betsdb',
        password: 'password123',
        port: 2345,
    });

     console.log("trying connection");
     const client = await pool.connect();
     console.log("succed");
});

When executing the "await pool.connect" it gives the error "Error: Connection terminated unexpectedly"

In docker i can interact with the DB without any problem, the password works and everyting alright. My container is running on http://localhost:2345 i verify this on docker desktop.

I really would appreciate any kind of solution please. I have been looking for a solution the past hours in stackoverflow found similar questions, different kind of possible solutions but nothing worked.

2

Answers


  1. A misconfiguration or network-related problem between your application and the PostgreSQL server frequently results in the Connection terminated unexpectedly error. Since PostgreSQL is being used inside of a Docker container, it’s essential to ensure adequate connectivity. Use the container name postgres-container instead of localhost in your connection configuration as Docker offers DNS resolution for container names. Additionally, ensure that your host machine’s network and your Docker container are both connected. Verify your host computer for any firewall settings or security applications that might prevent connections to the container’s port. Another thing that you can do it to set the second -p port number to 5432, as it is the default port for PostgreSQL, the two ports don’t have to match.

    Do let me know if this helps

    Login or Signup to reply.
  2. Change the port number of your postgres container to default 5432 and check the idle timeout in your ts file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search