使用 Docker 的 Postgres 连接问题

问题描述 投票:0回答:1

我在通过 docker 连接 Nest js 和 postgres 应用程序时遇到问题。我收到数据库连接错误。我希望如果我的数据库不存在,它应该在我运行 docker compose up 时自动创建。以下是我的文件。

Dockerfile

` 来自节点:16

# Set the working directory to /app
WORKDIR /app

# Copy package.json and package-lock.json to /app/
COPY package*.json .

# Install npm packages for development
RUN npm install

# Install ts-node globally
RUN npm install -g ts-node

# Copy the rest of the application code to /app/
COPY . .

# Run your database migrations
# RUN npm run migration:run

# Expose port for the development server if needed
EXPOSE 3002

# Start the development server
CMD [ "npm", "run", "start:dev" ]

Docker 撰写文件

# based off compose-sample-2, only we build nginx.conf into image
# uses sample HTML static site from https://startbootstrap.com/themes/agency/
version: '3'
services:
  api:
    build:
      context: .
      dockerfile: Dockerfile  # Use the development Dockerfile
    env_file:
      - '.env'
    # command: npm run migration:run && npm run start:dev
    volumes:
      - .:/app  # Mount the same directory as the production web service
    ports:
      - '3002:3002' 
    depends_on:
      - postgres
  postgres:
    image: postgres:13
    restart: always
    environment:
      POSTGRES_DB: boilerplate  # Change 'mydatabase' to the desired database name
      POSTGRES_USER: postgres   # Change 'myuser' to the desired username
      POSTGRES_PASSWORD: postgres
    ports:
      - '5431:5432'
    volumes:
      # - boilerplate:/var/lib/postgresql/data
      - ./db_data:/var/lib/postgresql/data
# volumes:
#   boilerplate:
ENV Variables
DATABASE_HOST=postgres
POSTGRES_DB=boilerplate
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres     DATABASE_URL=postgres://postgres:postgres@postgres:5431/boilerplate
DATABASE_PORT=5431

我尝试了多种方法,但找不到任何解决方案

postgresql docker nest
1个回答
0
投票

尝试为 Postgres 容器设置环境变量,如下所示:

POSTGRES_HOST_AUTH_METHOD: trust

这允许您无需使用密码即可建立连接。这至少可以让您测试您的 NodeJS 应用程序是否实际上无法访问 Postgres 数据库,或者是否存在授权问题(解决问题后显然应该将其删除)。

此外,如果您只想将数据库访问到其他容器,请使用 expose 而不是 port。这可确保无法从 Docker 部署外部自由访问数据库端口。

© www.soinside.com 2019 - 2024. All rights reserved.