Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image:

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

The TypeScript code I have is in 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("succeeded");
});

When I run "await pool.connect", I encounter the error "Error: Connection terminated unexpectedly".

In Docker, I can interact with the DB without any issues, the password works fine. My container is running at http://localhost:2345 as verified in Docker Desktop.

I would really appreciate any help or suggestions. I have been searching for a solution for hours on Stack Overflow and tried different solutions suggested by others but nothing has worked so far.

Answer №1

Modify the port number of your postgres container to the standard 5432 and review the idle timeout setting in your ts file.

Answer №2

When your application encounters a misconfiguration or network-related issue with the PostgreSQL server, it often leads to the

Connection terminated unexpectedly
error. To address this problem within a Docker container environment, it is crucial to ensure seamless connectivity. Instead of using localhost, consider utilizing the container name postgres-container in your connection setup as Docker supports DNS resolution for container names. Moreover, make sure that both your host machine's network and the Docker container are properly connected. Check the firewall settings and any security applications on your host computer that may be hindering connections to the container's port. Additionally, you can try setting the second -p port number to 5432, which is the default port for PostgreSQL - note that these two ports do not necessarily have to match.

If you find this information useful, please let me know.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the SequelizeConnectionRefusedError while using docker in conjunction with sequelize

My Docker configuration is set up as follows: web: image: ca9a385372b0 volumes: - .:/src ports: - "8000:8000" container_name: web links: - mysql mysql: image: 7666f75adb6b environment: container_name: mysql ports: - "6603: ...

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

React and Express facing CORS header challenge

I'm facing an issue with CORS despite trying various solutions found on Stack Overflow. My app uses Express/NodeJS as an API and React JS for the frontend. During development, the React app at http://localhost:3000 communicates successfully with the ...

GraphQL Apollo does not allow non-nullable fields to return null values

I'm currently diving into the world of graphql in order to implement it into a React website. I've hit a roadblock though, as I can't seem to understand why it's indicating that null is being returned even though I'm positive that ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

I'm curious if it's possible to set up both Tailwind CSS and TypeScript in Next.js during the initialization process

When using the command npx create-next-app -e with-tailwindcss my-project, it appears that only Tailwind is configured. npx create-next-app -ts If you use the above command, only TypeScript will be configured. However, running npx create-next-app -e with ...

express.js and socket.io compatibility perplexity

Server-Side Code: var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connection', function(client) { client.on('order', function(data) { io.emit('place_orde ...

How to Measure the Length of an Undefined Value in Jasmine Angular Unit Tests

Here's a function that I have: updateParts(enviromentContainsAllParts: PartsContainsAllParts): Observable<boolean> { const enviroment = cloneDeep(this.enviroment); enviroment.containsAllPart = enviromentContainsAllParts.containsAllPart ...

how can one exhibit the value of an object in TypeScript

Does anyone know how to properly display object values in forms using Angular? I can see the object and its values fine in the browser developer tools, but I'm having trouble populating the form with these values. In my *.ts file: console.log(this.pr ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Exploring the Power of TextEncoding in TS 2.8 within the Angular 6 Environment

I'm facing a challenging issue while trying to import TextEncoding in TS 2.8. I have installed it using npm and attempted to import it like this: import { TextDecoder } from 'text-encoding'; Alternatively, import { } from 'text-encod ...

Experiencing disconnection from SQL server while utilizing the Express.js API

Im currently working on an API that retrieves data from one database and posts it to another database, both located on the same server. However, I am facing issues with the connections. Initially, everything works fine when I run the app for the first time ...

Implementing conditional wildcard route redirection in an Angular routing module

Is there a way to manage redirect routes when users enter the wrong URL using wildcards controlled by conditions? In my project, I have 3 main modules that are separate, and each of them has specific conditions for user access based on roles. The issue I ...

Error: Nuxt not detected within the Docker container

I'm creating a docker setup for a nuxt 3 application. Here is my package.json configuration: { "private": true, "scripts": { "start": "nuxt start", "build": "nuxt build", &quo ...

When using RXJS, the method BehaviorSubject.next() does not automatically notify subscribers

In my project, I have a service set up like this: @Injectable({ providedIn: 'root' }) export class MyService { private mySubject = new BehaviorSubject({}); public currentData = this.mySubject.asObservable(); updateData(data: any) { ...

What is the best way to reproduce the appearance of a div from a web page when printing using typescript in Angular 4?

Whenever I try to print a div from the webpage, the elements of the div end up on the side of the print tab instead. How can I fix this issue? Below is my current print function: print(): void { let printContents, popupWin; printContents = document.getEl ...

The functionality of Handles Bars (hbs) is not working properly

After setting up my layouts folder inside the view directory, I encountered some issues. Here is my code: app.engine('hbs', hbs({extname: 'hbs', defualtLayout : 'layout' , layoutDir: __dirname + '/views/layouts'})); ...

Passport is encountering an error where user.authenticate is not recognized as a valid function

Although this question has been asked previously, I was unable to find a satisfactory answer. Here is the error message displayed in the console: TypeError: user.authenticate is not a function at /home/sinnedde/WebstormProjects/web-services/config/strateg ...