我有一个Node.js应用程序并设置了docker-compose。我试图在容器中使用Postgres DB。
这是docker-compose
version: "3"
services:
web:
build: .
ports:
- "3000:3000"
links:
- redis
- db
angular: # image of nginx
image: "qp-angular-nginx"
ports:
- "4200:80" # specify port forewarding
redis:
image: "redis:3"
ports:
- "6379:6379"
db:
image: "postgres:9.6"
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
volumes:
- pgdata:/var/lib/postgresql/data
dbadmin:
image: "myimage/phppgadmin"
ports:
- "8085:80"
environment:
POSTGRES_HOST: db
POSTGRES_PORT: 5432
volumes:
pgdata:
我已成功运行容器,甚至连接了数据库,但在发出数据库请求时出现此错误
"stack": {
"code": "ECONNREFUSED",
"errno": "ECONNREFUSED",
"syscall": "connect",
"address": "127.0.0.1",
"port": 5432
}
答案 0 :(得分:2)
如果从另一个docker容器连接到数据库,请在连接字符串中使用服务名称(在您的情况下为db
)。从错误消息看,您的配置似乎有问题。它尝试连接到localhost(127.0.0.1
)
答案 1 :(得分:0)
对于那些,您可以使用带有以下配置文件的最新结构项目:
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.APP_URL_DOCKER,
dialect: 'postgres'
},
test: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.APP_URL_DOCKER,
dialect: 'postgres'
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.APP_URL_DOCKER,
dialect: 'postgres'
}
};
您可以在postgres database
文件中指定.env
的服务名称。而且对您来说应该是有益的。
// .env file
APP_URL_LOCAL=127.0.0.1
APP_URL_DOCKER=db # database service name
APP_PORT=8000
APP_KEY=6dd63668dab9a309c7c59a2982126a43b064816925a40b9680d16e2665f41b676a87dae4d506712e6332479c82827993059ddefb607b65caa3534b66b20253ed
DB_USER=postgres
DB_PASSWORD=db_password
DB_NAME=db_name
DB_PORT_CONTAINER=5432
DB_PORT_LOCAL=5433