我正在尝试将NodeJS / PostgreSQL应用程序停靠,但我无法运行knex
迁移,我收到以下错误:
错误:连接ECONNREFUSED 172.18.0.2:15432
at TCPConnectWrap.afterConnect [as oncomplete](net.js:1161:14)
这是我的 docker-compose.yml :
version: "3"
services:
app:
build: .
depends_on:
- db
links:
- db
ports:
- "3000:3000"
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: users-microservice
DB_HOST: db
db:
image: postgres:10.4-alpine
expose:
- "5432"
ports:
- "15432:5432"
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: users-microservice
'app'服务的 Dockerfile :
FROM node:10.1-alpine
EXPOSE 3000 9229 15432
COPY . /home/app
WORKDIR /home/app
RUN npm install
RUN npm install -g knex
CMD ./scripts/start.sh
并在 start.sh 中,以下命令有效:
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$DB_HOST" -U "$POSTGRES_USER" -c '\d'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
所以我可以通过CLI连接到postgres,但knex不能,为什么呢?我搞错了,我是Docker的新手?
致以最诚挚的问候,
答案 0 :(得分:1)
我假设您在看到此错误消息时尝试在服务app
内运行命令(但也许您可以指定)?
我的猜测是,您尝试从db:15432
内尝试连接app
。注意,那说
ports:
- "15432:5432"
只确保您可以通过端口15432
上的主机计算机调用该服务。但是,如果您想在db
内拨打服务app
,则仍需使用db:5432
。
答案 1 :(得分:0)
@ the-bass的回答救了我。我将包含我的docker-compose.yml和knexfile.js文件,希望对于发现此问题的有此问题的人更加清楚。
我做错了是我没有在我的应用容器中正确设置主机环境变量。一旦将其更改为仅使用db(我的postgres容器的名称)并确保将端口包括在我的knexfile中,就可以了。
knexfile.js
require("dotenv").config();
module.exports = {
development: {
client: "pg",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: 5432,
},
pool: {
min: 2,
max: 10,
},
migrations: {
directory: "./data/migrations",
},
},
production: {
client: "pg",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: 5432,
},
pool: {
min: 2,
max: 10,
},
migrations: {
directory: "./data/migrations",
},
},
};
docker-compose.yml
version: "3.7"
services:
db:
image: postgres:12.2
restart: always
ports:
- 5432:5432
volumes:
- my-postgres-data:/var/lib/postgresql/data
environment:
- POSTGRES_USER=me
- POSTGRES_PASSWORD=password
- POSTGRES_DB=my-data
node-app:
image: node:12.16.2
command: sh -c "npm install && npm install -g knex && knex migrate:latest && npm start"
ports:
- 3001:3001
working_dir: /home/node/app
volumes:
- ./:/home/node/app
environment:
- NODE_ENV=development
- DB_HOST=db
- DB_USER=HG
- DB_PASSWORD=password
- DB_DATABASE=my-data
depends_on:
- db
links:
- db
volumes:
my-postgres-data: