我正在尝试配置一个docker compose,以使用postgres连接另一个容器上的nodejs应用程序(带有nest)。 从本地它可以正常工作,但是当在服务器上尝试它时它不起作用,就像 postgres 容器不接受连接。
services:
fe:
image: "feimage-dockerhub"
ports:
- 4800:80
api:
image: "apiimage-dockerhub"
depends_on:
- db
environment:
- POSTGRES_DB=dbname
- POSTGRES_USER=dbuser
- POSTGRES_PASSWORD=dbpass
- POSTGRES_HOST=db
- POSTGRES_PORT=5432
- HOST_URL=http://localhost:3000
- BCRYPT_SALT=10
restart: always
db:
container_name: db
image: "postgres"
environment:
POSTGRES_DB: dbname
POSTGRES_USER: dbuser
POSTGRES_PASSWORD: dbpass
restart: unless-stopped
volumes:
- db:/var/lib/postgresql/data
volumes:
db:
driver: local
我尝试运行两个容器并将它们放在同一个网络中,但连接也超时,通过 ping 到 postgres 服务,它会正确回复。
也许知道服务器已经安装了 portainer,并且其他具有非常相似配置的堆栈可以正常工作而不会出现问题,这会很有用。
也许我错过了一些东西
Client: Docker Engine - Community
Version: 23.0.2
API version: 1.42
Go version: go1.19.7
Git commit: 569dd73
Built: Mon Mar 27 16:16:30 2023
OS/Arch: linux/amd64
Context: default
Server: Docker Engine - Community
Engine:
Version: 23.0.2
API version: 1.42 (minimum version 1.12)
Go version: go1.19.7
Git commit: 219f21b
Built: Mon Mar 27 16:16:30 2023
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.6.20
GitCommit: 2806fc1057397dbaeefbea0e4e17bddfbd388f38
runc:
Version: 1.1.5
GitCommit: v1.1.5-0-gf19387a
docker-init:
Version: 0.19.0
GitCommit: de40ad0
谢谢
我尝试了一个简单的配置来检查容器之间的通信,使用 psql 从 postgres 主机连接到另一个主机,它仅在本地工作,在服务器上存在相同的问题
version: "3"
services:
db:
image: "postgres"
environment:
POSTGRES_DB: vault
POSTGRES_USER: root
POSTGRES_PASSWORD: root
db2:
image: "postgres"
environment:
POSTGRES_DB: vault
POSTGRES_USER: root
POSTGRES_PASSWORD: root
这是配置数据库连接的部分
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { DataSourceOptions, EntitySchema } from 'typeorm';
export function typeOrmConfig(
entities: EntitySchema[] = [],
migrations: string[] = [],
): TypeOrmModuleOptions & Partial<DataSourceOptions> {
console.log(process.env)
const res: TypeOrmModuleOptions = {
type: 'postgres',
host: process.env.POSTGRES_HOST,
synchronize: true,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
dropSchema:
process.env.DROP_SCHEMA === undefined
? false
: Boolean(process.env.DROP_SCHEMA),
migrationsTableName: '__migrations__',
migrations,
entities,
};
if (process.env.POSTGRES_PORT) {
return {
...res,
port: process.env.POSTGRES_PORT
? Number(process.env.POSTGRES_PORT)
: 5432,
};
}
return res;
}
这是从 process.env 打印的内容
{
JWT_EXPIRATION_TIME: '100000000000000',
NODE_VERSION: '18.18.0',
HOSTNAME: '30bd4fc3d1af',
ENV_FILE: 'prod',
YARN_VERSION: '1.22.19',
HOME: '/root',
HOST_URL: 'http://localhost:3000',
BCRYPT_SALT: '10',
POSTGRES_PASSWORD: 'dbpass',
PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
POSTGRES_HOST: 'db',
POSTGRES_USER: 'dbuser',
PWD: '/usr/app',
POSTGRES_DB: 'dbname',
POSTGRES_PORT: 5432
}
无论如何,使用 psql -h 连接也无法工作,它也会超时