简体   繁体   中英

Nestjs Typeorm + Postgres Docker Compose doesn't seem to work

I have a Nestjs API + TypeORM with a active PostgreSQL connection. I am currently trying to dockerize the whole api.

Dockerfile:

ENV DIR=/home/node/app
RUN mkdir -p ${DIR}
WORKDIR ${DIR}
COPY package*.json ./

RUN npm install

RUN npm install -g @nestjs/cli

RUN npm run build

COPY . .

EXPOSE 3000

CMD ["node", "dist/main.js"]

Typeorm Config:

require('dotenv').config()
@Module({
  imports: [
    TypeOrmModule.forRoot({
    type: "postgres",
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    port: 5432,
    database: "postgres",
    entities: ["dist/**/*.entity{.ts,.js}"],
    synchronize: false }),

.env file:

DB_HOST=postgres
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=test

docker-compose.yaml file:

version: "3.9"
services:
    middleware:
        build: .
        container_name: "middleware"
        ports:
            - "3000:3000"
        depends_on:
            - postgres
        env_file:
            - .env
    postgres:
        image: "postgres:12"
        restart: always
        container_name: "postgres"
        environment:
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=${DB_PASSWORD}
            - POSTGRES_DB=postgres
        ports:
            - "5433:5432"
        volumes:
            - api:/var/lib/postgresql/data
            - ./src/migs/001_create.sql:/docker-entrypoint-initdb.d/001_create.sql

volumes:
    api:

I also have a.sql file, which creates the first tables and fills them with data, but i guess it is not relevant for my question. From what i have seen, the problems seems to be with the.env file, but i don't understand what am I doing wrong? I am accessing the postgres host, which is also the name of the running container, i don't believe the problem lies here.

I can access the postgres container from outside via winpty docker exec -it postgres psql -U postgres -h postgres postgres

The tables are created successfully, has to be something with the.env file. The console output from api is:

Unable to connect to the database. Retrying (8)...

error: no PostgreSQL user name specified in startup packet

Any help is welcomed: Thanks in advance, PS. I found similar topics in stackoverflow, but didn't seem to fix my problem. If i by any chance have missed an already answered topic, please point me to it.

clear your volume and run docker-compose again

Putting all environment variables for postgres into the.env file

POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=postgres

and then telling docker-compose to use the.env file for the postgres container solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM