基本上,我有一个Nodejs项目,通过knex连接到postgres数据库,我使用CircleCI进行测试。它可以工作,但偶尔会因“错误:连接ECONNREFUSED 127.0.0.1:5432”而导致构建失败,我无法弄清楚原因;它在我的机器上没有问题,在构建中必须有所不同。
运行以创建测试数据库的文件如下:
'use strict';
require('dotenv').config();
const connectionOptions = require(`${process.cwd()}/knexfile.js`)[`${process.env.NODE_ENV}`];
const knex = require('knex')(connectionOptions);
console.log('New connection to default postgres database made');
// Remove all other connections to test database
knex.raw(`select pg_terminate_backend(pid) from pg_stat_activity where datname = '${process.env.PG_TEST_DATABASE}'`)
.then(() => {
console.log('Removed all other connections to the test database');
// Drop test database if it exists
return knex.raw(`DROP DATABASE IF EXISTS ${process.env.PG_TEST_DATABASE};`);
})
.then(() => {
console.log('Dropped test database (if it existed)');
// Create test database
return knex.raw(`CREATE DATABASE ${process.env.PG_TEST_DATABASE};`);
})
.then(() => {
console.log('Test database created');
return process.exit();
});
当它发生时,错误将发生在我连接后第一次尝试使用postgres做任何事情时,我是否尝试删除数据库,删除其他连接等等。目前,当我尝试执行'select pg_terminate_backend'行时会发生这种情况。
我对Postgres的设置是:
const connectionOptions = {
client: 'pg',
version: '7.4.1',
connection: {
host: '127.0.0.1',
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
port: parseInt(process.env.PG_PORT) || 5432
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: '_migrations',
directory: './migrations',
},
seeds: {
directory: './seeds/development'
}
};
我的circleci yml文件如下:
version: 2
jobs:
build:
working_directory: ~/project
docker:
- image: circleci/node:8.9.4
# The below environemnt is where you set the .env variables used throughout node
environment:
NODE_ENV: test
PG_USER: jerrodq2
PG_DATABASE: freelancing_project
PG_TEST_DATABASE: freelancing_project_test
PG_PORT: 5432
- image: postgres:10.3
environment:
POSTGRES_USER: jerrodq2
POSTGRES_DB: freelancing_project
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run:
name: Install local dependencies
command: npm install
- run:
name: Create database
command: npm run db:reset:test
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}
# run tests!
- run:
name: Running Tests
command: npm run test
对于任何有兴趣的人,我都能找到解决方案。按照Linas在上面的评论中的建议,我找到了适当的代码,等待postgres开始进入下一步之前,我只是添加了一个命令,等待5432端口打开,然后创建数据库,如下所示:
- run:
name: Install local dependencies
command: npm install
- run:
name: Wait for Postgres to start
command: dockerize -wait tcp://localhost:5432 -timeout 1m
- run:
name: Create database
command: npm run db:reset:test