我正在使用TypeScript、Express和Sequelize
构建API服务器。
这是我的database
连接类。
export class Database {
private _sequelize: Sequelize;
private config: DBConfigGroup = dbConfig;
private env = process.env.NODE_ENV as string;
constructor() {
this._sequelize = new Sequelize({
dialect: 'postgres',
database: this.config[this.env].database,
username: this.config[this.env].username,
password: this.config[this.env].password,
host: this.config[this.env].host,
});
}
async connect(): Promise<void> {
try {
console.log('start connect');
await this._sequelize.authenticate();
console.log('Connection has been established successfully.'.green.bold);
} catch (error) {
console.error('Unable to connect to the database:'.red.bold, error);
}
}
async close(): Promise<void> {
try {
await this._sequelize.close();
console.log('Connection has been close successfully.'.red.bold);
} catch (error) {
console.error('Unable to close to the database:'.yellow.bold, error);
}
}
get sequelize(): Sequelize {
return this._sequelize;
}
}
所以在我的server.ts
文件中,我正在调用这个东西
dotenv.config({
path: './config/environments/config.env',
});
const database = new Database();
console.log('Init db');
database
.connect()
.then(() => {
console.log('success db ininit');
})
.catch((err) => {
console.log('fail db init: ', err);
});
/**
* Server Activation
*/
const server = app.listen(PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold);
});
我的本地开发环境一切正常。
但是当我尝试使用此配置在 docker compose
中运行时,出现问题。
// docker-compose.yml
version: '3.4'
services:
api:
stdin_open: true
tty: true
build:
context: ./api
dockerfile: Dockerfile.dev
ports:
- "5000:5000"
volumes:
- /app/node_modules
- ./api:/app
这是我的Dockerfile.dev
文件
FROM node:alpine
ENV NODE_ENV=development
WORKDIR /app
EXPOSE 5000
COPY package.json package-lock.json* ./
RUN npm install && npm cache clean --force
COPY . .
CMD ["npm", "run", "dev:docker"]
但问题是当我运行 docker-compose up --build
命令时,我只能看到这些日志
api_1 | Init db
api_1 | start connect
api_1 | Server running in development mode on port 5000
基本上,无论sequelize.authenticate()
成功或失败,都没有响应,只会打印出Server running in development mode on port 5000
,之后什么也没有了。
为什么在Docker中不像在本地那样工作?有我漏掉的任何配置吗?
谢谢。
cloud_sql_proxy
,对吗? - BYK34.69.33.26
,我怀疑问题不在于sequelize
本身,因为如果我使用相同的配置更改到另一个实例上的mySql
,它可以正常工作。 - Varis Darasirikul