我在 Google Cloud Run 中部署了一个 NestJS 应用程序,我能够连接到 Cloud SQL 数据库,但是我在运行 TypeORM 迁移时遇到了问题。我没有使用 ormconfig.json
,而是创建了一个导出 TypeORM 连接对象的 database.config.ts
文件,以便它可以异步加载:
import { config } from './config/database.config';
...
imports: [
TypeOrmModule.forRootAsync({
useFactory: () => config,
}),
]
我的 database.config.ts
文件包含以下内容:
import { ConnectionOptions } from 'typeorm';
import 'reflect-metadata';
export const prod = process.env.NODE_ENV === 'production';
export const config: ConnectionOptions = {
name: 'default',
type: 'mysql' as any,
driver: 'mysql',
database: 'test_db',
synchronize: true,
logging: true,
entities: ['dist/**/*.entity{.ts,.js}'],
cli: {
migrationsDir: 'migrations',
},
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
// Production Mode
...(prod && {
extra: {
socketPath: '/cloudsql/{PROJECT_ID}:us-central1:{DB_NAME}',
},
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
synchronize: false,
logging: true,
migrationsRun: false,
migrations: ['dist/migrations/*{.js}'],
cli: { migrationsDir: 'src/migrations' },
}),
};
export default config;
用于初始化 Cloud Run 实例的 Dockerfile 具有以下内容:
# use node 12 image
FROM node:12 as base
# set our working directory
WORKDIR /app
FROM base as development
# copy over dependecy manifests to install
COPY package*.json ./
# install production dependencies and copy them to a temp folder, we will use this for the final build step
RUN npm install --production
RUN cp -R node_modules /tmp/node_modules
# Install all dependcies
RUN npm install
# Copy source code
COPY . ./
# lint, unit test, e2e test and build our app
FROM development as builder
RUN npm run lint
RUN npm run test:cov
RUN npm run test:e2e
RUN npm run build
# release includes bare miniumum to run the app
FROM base as release
COPY --from=builder /tmp/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
# Run the web service on container boot
CMD ["npm", "run", "start:prod"]
最后,我的 package.json 使用以下脚本启动应用程序:
"scripts": {
...
"prod:migration": "npm i -g typeorm && npm run typeorm:migration",
"start:prod": "npm run prod:migration && node dist/src/main",
"typeorm:migration": "ts-node --transpile-only ./node_modules/typeorm/cli.js migration:run",
"typeorm:revert": "ts-node --transpile-only ./node_modules/typeorm/cli.js migration:revert"
...
},
在部署时,我会收到错误消息,提示找不到 typeorm/ts-node。一些小的调整将允许应用程序成功部署,但没有任何迁移成功运行。我想知道我是否走在正确的道路上,或者我是否可以进行任何更改以使迁移在应用程序启动时成功运行。