1、配置Dockerfile文件
FROM node:latest
# 创建工作目录
RUN mkdir -p /app
# 指定工作目录
WORKDIR /app
# 复制当前代码到/app工作目录
COPY . ./
# npm 源,选用国内镜像源以提高下载速度
RUN npm config set registry https://registry.npmmirror.com/
# npm 安装依赖
RUN npm install
# 打包
RUN npm run build
# 暴露容器端口
EXPOSE 9000
# 启动服务
CMD node ./dist/main.js
2、配置docker-compose.yml文件
services:
mysql:
container_name: mysql_qinlj
image: mysql:8.0.13
ports:
- 3339:3306
restart: always
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h localhost"]
environment:
MYSQL_ROOT_PASSWORD: '123456'
MYSQL_DATABASE: 'node-server'
volumes:
- ./data:/var/lib/mysql
networks:
- node-server
server:
container_name: node-server
build:
context: .
dockerfile: Dockerfile
ports:
- 6605:9000
restart: always
networks:
- node-server
depends_on:
mysql:
condition: service_healthy
networks:
node-server:
driver: bridge
ipam:
config:
- subnet: 172.112.0.0/16
gateway: 172.112.0.1
3、配置nestjs连接MySQL服务
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
// 应用程序的根模块
@Module({
imports: [
// 根据环境变量配置env文件
ConfigModule.forRoot({
cache: true,
envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],
}),
// 配置数据库
TypeOrmModule.forRoot({
type: 'mysql',
host: 'mysql_qinlj',
port: 3306,
username: 'root',
password: '123456',
database: 'node-server',
// 引用实体,制动autoLoadEntities后,通过forFeature()方法注册的每个实体都将自动添加到配置对象的entities数组中
// entities: [User],
autoLoadEntities: true,
// synchronize: true不能在生产环境中使用,否则可能会丢失生产数据
synchronize: true,
}),
UserModule,
AuthModule,
],
controllers: [AppController],
providers: [
{
// 配置全局导航守卫
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
AppService,
],
})
export class AppModule {}
4、运行docker
docker-compose up -d
访问ip:port/api