You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从本地CLI向Docker容器执行TypeORM数据库迁移?

解决TypeORM CLI无法连接Docker容器内PostgreSQL的方案

方案1:接入Docker容器网络执行迁移

  • 先通过docker network ls查看你的Docker Compose项目对应的网络名称(默认格式为项目目录名_default)
  • 直接在容器网络内运行TypeORM命令,挂载本地代码目录避免镜像重复构建:
docker run --rm -v $(pwd):/app --network 你的网络名称 node:18-alpine sh -c "cd /app && npx typeorm migration:run -d src/data-source.ts"
  • 或者如果应用容器已运行,直接进入容器执行命令:
docker exec -it 你的应用容器名称 npx typeorm migration:run -d src/data-source.ts

方案2:动态切换数据库主机配置

  • 在TypeORM数据源配置文件中,通过环境变量区分本地和容器环境:
// src/data-source.ts
import { DataSource } from "typeorm";

export default new DataSource({
  type: "postgres",
  host: process.env.DB_HOST || "localhost",
  port: 5432,
  username: "你的数据库用户名",
  password: "你的数据库密码",
  database: "你的数据库名",
  entities: ["src/entities/**/*.ts"],
  migrations: ["src/migrations/**/*.ts"],
});
  • 在docker-compose.yml中给应用容器配置环境变量DB_HOST: postgres(对应你的PostgreSQL服务名称)
  • 同时在PostgreSQL服务中添加端口映射,让本地能访问容器内的数据库:
services:
  postgres:
    image: postgres:15
    ports:
      - "5432:5432"
    # 其他配置...
  • 本地运行迁移时,直接执行npx typeorm migration:run -d src/data-source.ts即可

方案3:在Docker Compose中添加迁移专用服务

  • 修改docker-compose.yml,新增一个专门执行迁移的服务:
services:
  postgres:
    image: postgres:15
    environment:
      POSTGRES_USER: 你的用户名
      POSTGRES_PASSWORD: 你的密码
      POSTGRES_DB: 你的数据库名
    volumes:
      - postgres-data:/var/lib/postgresql/data

  app:
    build: .
    depends_on:
      - postgres
    environment:
      DB_HOST: postgres

  migrate:
    build: .
    depends_on:
      - postgres
    command: npx typeorm migration:run -d src/data-source.ts
    environment:
      DB_HOST: postgres
    volumes:
      - ./src:/app/src
  • 执行迁移时只需运行:
docker-compose run --rm migrate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:01:11