我正在尝试使用 docker-compose 将我的 nodejs 应用程序与 postgres 连接。
这是我的docker-compose.yml
version: "3.9"
services:
db:
container_name: db
image: postgres
restart: always
environment:
POSTGRES_USER: agoodusername
POSTGRES_PASSWORD: astrongpassword
POSTGRES_DB: dbname
volumes:
- ./pgdata:/var/lib/postgresql/data
ports:
- 5433:5432
networks:
- postgres
pgadmin:
container_name: pgadmin4
platform: linux/amd64
image: dpage/pgadmin4
restart: always
depends_on:
- db
environment:
PGADMIN_DEFAULT_EMAIL: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322272e2a2d0322272e2a2d6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>
PGADMIN_DEFAULT_PASSWORD: root
ports:
- 5050:80
networks:
- postgres
be:
container_name: be
depends_on:
- db
build:
context: .
dockerfile: ./Dockerfile
ports:
- 3333:3333
networks:
- postgres
networks:
postgres:
driver: bridge
(请注意,我尝试过使用和不使用网络
)
我的index.ts:
import { Entity, Column, PrimaryGeneratedColumn, createConnection } from "typeorm";
import express from 'express';
@Entity()
class Photo {
@PrimaryGeneratedColumn()
id?: number;
@Column()
name?: string;
@Column()
description?: string;
@Column()
filename?: string;
@Column()
views?: number;
@Column()
isPublished?: boolean;
}
const createCon = async () => {
let retries = 5;
while(retries) {
try {
const connection = await createConnection({
type: 'postgres',
url: 'postgres://agoodusername:astrongpassword@db:5433/dbname',
synchronize: false,
entities: [Photo]
});
console.log(connection.isConnected);
break;
}
catch(e) {
console.log(e);
retries -= 1;
await new Promise(res => setTimeout(res, 5000));
}
}
}
const app = express();
app.listen(3333, '0.0.0.0', () => {
createCon();
console.log("Server is running at port 3333");
})
Dockerfile:
FROM node:12.18.1-alpine
WORKDIR /app
COPY . .
RUN yarn
CMD ["yarn", "start"]
EXPOSE 3333
我在自己的 docker 容器上运行 postgres,在另一个容器上运行 Node (没有 docker-compose),一切正常。
此外,pgadmin 容器无法连接到 postgres 容器,我已经提供了正确的主机名(在本例中为 db)和正确的主机地址(通过运行 docker inform db | grep IPAddress 获取) >)
以下是来自 Nodejs 容器的日志:
yarn run v1.22.4
$ ts-node index.ts
Server is running at port 3333
Error: connect ECONNREFUSED 172.20.0.2:5433
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '172.20.0.2',
port: 5433
}
如果您想要完整的项目检查 this repo
最佳答案
你使用的端口不正确,5433端口暴露在外面,所以它只在主机上打开,当使用docker ip时,你应该使用运行docker内部的端口,即5432
关于node.js - Postgres 不接受使用 docker-compose 的其他容器的任何连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69061621/