【发布时间】:2019-01-23 12:42:44
【问题描述】:
基本上,我有一个 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 执行任何操作时,无论我尝试删除数据库、删除其他连接等。目前,当我尝试执行“选择”时会发生此错误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
【问题讨论】:
-
只是猜测,但也许 PostgreSQL 无法及时启动?尝试等待数据库守护进程的端口打开:stackoverflow.com/a/27601038/200603
-
感谢Linas的建议,我一直在尝试不同的东西,每次我认为它已经解决了,它会再次发生。他们在您的建议中使用的代码是另一种语言,我将不得不查看 javascript 或 circleci 版本,但是您建议我把它放在哪里?在 yml 文件中?创建测试数据库 js 文件?
标签: javascript node.js postgresql knex.js circleci