Riku
Riku

Reputation: 157

NestJS and TypeORM fail to connect my local Postgres database. Claims my database does not exist, even tho it does

I have NestJS application that uses TypeORM to connect to my local database. I create database with shell script:

#!/bin/bash
set -e

SERVER="my_database_server";
PW="mysecretpassword";
DB="my_database";

echo "echo stop & remove old docker [$SERVER] and starting new fresh instance of [$SERVER]"
(docker kill $SERVER || :) && \
  (docker rm $SERVER || :) && \
  docker run --name $SERVER -e POSTGRES_PASSWORD=$PW \
  -e PGPASSWORD=$PW \
  -p 5432:5432 \
  -d postgres

# wait for pg to start
echo "sleep wait for pg-server [$SERVER] to start";
SLEEP 3;

# create the db 
echo "CREATE DATABASE $DB ENCODING 'UTF-8';" | docker exec -i $SERVER psql -U postgres
echo "\l" | docker exec -i $SERVER psql -U postgres

After that, it logs databases: enter image description here

Then I fire up my application, and I encounter error "error: database "my_database" does not exist"

I use following code to connect to database:

static getDatabaseConnection(): TypeOrmModuleOptions {
        console.log(require('dotenv').config())
        return {
            type: 'postgres',
            host: "127.0.0.1",
            port: 5432,
            username: 'postgres',
            password: 'mysecretpassword',
            database: 'my_database',
            entities: ['dist/**/*.entity{.ts,.js}'],
            synchronize: true,
        };
    }

Any ideas where do I go wrong?

Upvotes: 2

Views: 8222

Answers (3)

Ramazan Aliskhanov
Ramazan Aliskhanov

Reputation: 168

  1. "localhost" isn't address of your docker container. Which address uses docker you can look running command:

    $ docker inspect {your_container_name}

for me is: 172.17.0.2

enter image description here

  1. Try enable SSL, adding next configuration lines:

ssl: true,
extra: { ssl: { rejectUnauthorized: false } }

Upvotes: 3

Mattias
Mattias

Reputation: 840

When connecting to a docker instance, you should usually use the service name. In this case I guess it is my_database_server as host parameter.

return {
            type: 'postgres',
            host: "my_database_server",
            port: 5432,
            username: 'postgres',
            password: 'mysecretpassword',
            database: 'my_database',
            entities: ['dist/**/*.entity{.ts,.js}'],
            synchronize: true,
        };

Upvotes: 4

Dmitrii Tkachenko
Dmitrii Tkachenko

Reputation: 586

Try using localhost instead of 127.0.0.1

Upvotes: 0

Related Questions