NodeJS 错误:在Docker Compose中连接到Localhost上的Postgres

m3eecexj  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(121)

我尝试使用docker-compose来使用Node.js和PostgreSQL(在localhost上)构建应用程序,但它仍然显示此错误。

connect ECONNREFUSED 127.0.0.1:15432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
   errno: -111,
   code: 'ECONNREFUSED',
   syscall: 'connect',
   address: '127.0.0.1',
   port: 15432
 }

下面有我的docker-compose.yml和Dockerfile,我应该如何修复?
docker-compose.yml:

version: "3.8"

services:
  database:
    image: postgres:alpine
    container_name: postgres
    environment:
      POSTGRES_DB: postgres
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    ports:
      - 15432:5432
  
  node:
    container_name: node-ts
    depends_on:
      - database
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 3000:3000

Dockerfile:

FROM node:18
WORKDIR /app
COPY ./ /app
RUN npm install
EXPOSE 3000
CMD npm start

我尝试在docker-compose.yml中添加这些语法来解决这个错误,但都没有成功。

links:
  - "database:postgres"
extra_hosts:
  - "host.docker.internal:172.0.0.1"
environment:
  DATABASE_URL: jdbc:postgresql://localhost:15432/postgres
af7jpaap

af7jpaap1#

导出的端口只显示了你如何从外部访问postgresql(从你的机器)。从intern,也是其他容器,你可以访问数据库:5432上的postgresql。
所以正确的DATABASE_URL是jdbc:postgresql://database:5432/postgres

相关问题