今天我尝试 dockerize 一个完整的应用程序(前端、API 和数据库),以便我可以将它部署在本地机器或/和虚拟机上。
做的时候:
docker-compose up
当我尝试启动我的 API 时,我得到了一个“Connect ECONNREFUSED”,该 API 将使用以下环境变量连接到数据库(它在后台使用 Sequelize):
DATABASE_URL: "postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-jy95}@db:5432/${POSTGRES_DB:-sourcecode}"
在 docker docs 中,它说:
Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.
在 PostgreSQL docs 中,我们可以看到 postgresql:// 也是有效的:
The URI scheme designator can be either postgresql:// or postgres://. Each of the URI parts is optional.
这是我完整的 docker-compose.yml 文件:
version: '3.7'
services:
frontend:
image: jy95/sourcecode-front
restart: always
depends_on:
- api
ports:
- "80:3000"
- "443:3000"
environment:
API_SERVER: "api:8080"
CDN_SERVER: "api:8080/files"
api:
image: jy95/sourcecode_api
restart: always
ports:
- "8080:3000"
depends_on:
- db
environment:
DATABASE_URL: "postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-jy95}@db:5432/${POSTGRES_DB:-sourcecode}"
# use a env file if you want to use other values that default ones
# https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option
db:
image: postgres:12-alpine
restart: always
ports:
- "5432:5432"
environment:
# use a env file for that part later
# https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option
POSTGRES_USER: postgres
POSTGRES_PASSWORD: jy95
POSTGRES_DB: sourcecode
POSTGRES_PORT: 5432
# If we want to access more easily to the database (not recommended)
# PGDATA: /var/lib/postgresql/data/pg_data
#volumes:
# - pg_data:/var/lib/postgresql/data/pg_data
先谢谢您的帮助
PS:镜像已经在 Docker Hub 上
最佳答案
你的评论其实是一个很大的线索:
“这是我使用的命令(如我所见,我使用了“depends_on”来确保在 API 之前需要数据库。错误是:SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432 我不明白: docker 文档不是最新的?”
看起来您的 api 容器正在尝试向 localhost 而不是 db:5432 发送(正如您指出的 db 是一个 DNS 名称,它不太可能解析为 127.0.0.1(IP 保留给 localhost)
快速调试:
运行:
docker exec -it sh
(在容器中)
apk 添加busybox-extras
然后:
telnet 127.0.0.1 5432 -> 你会看到这是无法访问的
然而
telnet db 5432 -> 这完全没问题
此外你可以运行
nslookup db -> 因为我们已经建立了这个 dns 名称 (db) 应该是可解析的
我曾尝试将 network_mode: host 添加到 api(在 docker-compose.yml 中),但这会导致您的应用程序崩溃。
在这一点上,我建议查看 api 的代码并查找对 127.0.0.1:5432 的任何引用
如果你运行 docker exec -it sh
然后:
打印环境
您将看到 DB_URL 环境变量设置为:
postgresql://postgres:jy95@db:5432/sourcecode
但是你确定这个 ENV-VAR 被 api 使用了吗?
(也许您已经通过示例注释了一些代码,并且您仍在使用不同的连接字符串)
关于postgresql - Docker-compose : Postgresql ECONNREFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357796/