You need to enable JavaScript to run this app. Heroku部署后端运行TypeORM迁移报Postgres pg_hba.conf SSL off错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Heroku部署后端运行TypeORM迁移报Postgres pg_hba.conf SSL off错误求助

你在app.module.ts中配置的SSL参数仅作用于NestJS应用运行时的数据库连接,执行typeorm:migration:run命令调用的是TypeORM独立CLI工具,默认不会加载Nest模块内的TypeORM配置,因此SSL配置未生效,导致报错提示SSL off。

以下是对应解决方案:

方案1:适配TypeORM 0.2.x版本

在项目根目录新增ormconfig.js配置文件,TypeORM CLI会自动读取该文件的配置:

module.exports = {
  type: 'postgres',
  url: process.env.DATABASE_URL,
  ssl: {
    required: true,
    rejectUnauthorized: false
  },
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/migrations/**/*.js'],
  cli: {
    migrationsDir: 'src/migrations'
  }
}

配置完成后直接执行原有迁移命令即可生效。


方案2:适配TypeORM 0.3.x及以上版本

0.3+版本已弃用ormconfig配置,需单独编写数据源配置文件:

  1. 在项目根目录新建data-source.ts:
import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { config } from 'dotenv';

// 加载.env环境变量
config();
const configService = new ConfigService();

export default new DataSource({
  type: 'postgres',
  url: configService.get('DATABASE_URL'),
  ssl: {
    required: true,
    rejectUnauthorized: false,
  },
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/migrations/**/*.js'],
});
  1. 修改package.json中的迁移命令,指定数据源文件:
"typeorm:migration:run": "typeorm-ts-node-commonjs migration:run -d data-source.ts"

临时快速验证方案

如果需要临时测试,可以在执行迁移命令时强制指定PostgreSQL SSL模式:

PGSSLMODE=require npm run typeorm:migration:run

注意事项

  • 确保你的tsconfig.json已经配置了允许CommonJS模块导入,否则执行CLI命令可能会报错。
  • 部署到Heroku前要先完成TS编译,确保dist目录下存在编译后的实体和迁移文件,在Heroku上执行远程迁移时直接运行heroku run npm run typeorm:migration:run即可。

内容的提问来源于stack exchange,提问作者mojo42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 17:36:04