ECONNREFUSED for Postgres on nodeJS with dockers [英] ECONNREFUSED for Postgres on nodeJS with dockers

查看:17
本文介绍了ECONNREFUSED for Postgres on nodeJS with dockers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 postgresql 构建在 NodeJS 上运行的应用程序.我使用 SequelizeJS 作为 ORM.为避免使用真正的 postgres 守护进程并在我自己的设备上使用 nodejs,我将容器与 docker-compose 一起使用.

I'm building an app running on NodeJS using postgresql. I'm using SequelizeJS as ORM. To avoid using real postgres daemon and having nodejs on my own device, i'm using containers with docker-compose.

当我运行 docker-compose up它启动 pg 数据库

when I run docker-compose up it starts the pg database

database system is ready to accept connections

和 nodejs 服务器.但是服务器无法连接到数据库.

and the nodejs server. but the server can't connect to database.

Error: connect ECONNREFUSED 127.0.01:5432

如果我尝试在不使用容器的情况下运行服务器(在我的机器上使用真正的 nodejs 和 postgresd),它可以工作.

If I try to run the server without using containers (with real nodejs and postgresd on my machine) it works.

但我希望它与容​​器一起正常工作.我不明白我做错了什么.

But I want it to work correctly with containers. I don't understand what i'm doing wrong.

这里是docker-compose.yml文件

web:
  image: node
  command: npm start
  ports:
    - "8000:4242"
  links:
    - db
  working_dir: /src
  environment:
    SEQ_DB: mydatabase
    SEQ_USER: username
    SEQ_PW: pgpassword
    PORT: 4242
    DATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase
  volumes:
    - ./:/src
db:
  image: postgres
  ports:
  - "5432:5432"
  environment:
    POSTGRES_USER: username
    POSTGRES_PASSWORD: pgpassword

有人可以帮我吗?

(喜欢 docker 的人 :) )

(someone who likes docker :) )

推荐答案

你的 DATABASE_URL 指的是 127.0.0.1,也就是 环回适配器(更多此处).这意味着连接到我自己".

Your DATABASE_URL refers to 127.0.0.1, which is the loopback adapter (more here). This means "connect to myself".

在同一主机上运行两个应用程序(不使用 Docker)时,它们都可以在同一个适配器(也称为 localhost)上寻址.

When running both applications (without using Docker) on the same host, they are both addressable on the same adapter (also known as localhost).

在容器中运行这两个应用程序时,它们不像以前那样都在本地主机上.相反,您需要将 web 容器指向 docker0 适配器上的 db 容器的 IP 地址 - docker-compose> 为您设置.

When running both applications in containers they are not both on localhost as before. Instead you need to point the web container to the db container's IP address on the docker0 adapter - which docker-compose sets for you.

变化:

127.0.0.1CONTAINER_NAME(例如 db)

示例:

DATABASE_URL: postgres://username:pgpassword@127.0.0.1:5432/mydatabase

DATABASE_URL: postgres://username:pgpassword@db:5432/mydatabase

这要归功于 Docker 链接:web 容器有一个文件 (/etc/hosts),其中一个 db 条目指向db 容器所在的 IP.这是系统(在本例中为容器)在尝试解析主机名时首先查看的位置.

This works thanks to Docker links: the web container has a file (/etc/hosts) with a db entry pointing to the IP that the db container is on. This is the first place a system (in this case, the container) will look when trying to resolve hostnames.

这篇关于ECONNREFUSED for Postgres on nodeJS with dockers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆