英文:
ERROR: Connect to Postgres on Localhost in Docker Compose
问题
我尝试使用docker-compose构建一个使用Node.js和PostgreSQL(在本地主机上)的应用程序,但仍然显示此错误。
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
英文:
I try to use docker-compose to build an application using Node.js and PostgreSQL(on localhost), but it still shows this error.
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
}
There are my docker-compose.yml and Dockerfile below, how should I fix?
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
I try to add these syntax in docker-compose.yml
to solve this error but none of them succeeded.
links:
- "database:postgres"
extra_hosts:
- "host.docker.internal:172.0.0.1"
environment:
DATABASE_URL: jdbc:postgresql://localhost:15432/postgres
答案1
得分: 1
导出的端口仅显示如何从您的计算机外部访问PostgreSQL。从内部,也可以访问数据库上的PostgreSQL:5432端口。
因此,正确的DATABASE_URL是jdbc:postgresql://database:5432/postgres
。
英文:
The exported port only shows, how can you access the postgresql externally (from your machine). From intern, also for other containers, you can access the postgresql on database:5432.
So the correct DATABASE_URL is jdbc:postgresql://database:5432/postgres
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论