K8s中部署若依微服务

在 Kubernetes 集群中完整部署若依微服务(RuoYi-Cloud)的实践记录,包含基础设施部署、Nacos 配置、Docker 镜像构建及 K8s 编排的全流程

6493 字

K8s 中部署若依微服务

整体架构

 1                    【 外部访问流量 】
 2                           │
 3                           ▼
 4              ┌─────────────────────────────────┐
 5              │      NodePort (各服务端口)       │
 6              └────────────┬────────────────────┘
 7                           │
 8              ┌────────────▼────────────┐
 9              │   ruoyi-ui (Nginx 80)   │  -- 前端页面,反向代理 /prod-api/ → gateway
10              │   NodePort 30081        │
11              └────────────┬────────────┘
12                           │ /prod-api/**
13                           ▼
14              ┌─────────────────────────┐
15              │   ruoyi-gateway (8080)  │  -- 网关:路由分发、鉴权、验证码、Sentinel
16              │   NodePort 30080        │
17              └────────────┬────────────┘
18                           │
19            ┌──────────────┼──────────────┬──────────────┐
20            ▼              ▼              ▼              ▼
21     ┌───────────┐  ┌───────────┐  ┌───────────┐  ┌───────────┐
22     │auth(9200) │  │system(9201)│ │ gen(9202) │  │file(9300) │ ... (其他微服务)
23     └─────┬─────┘  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘
24           │              │              │              │
25           └──────────────┴──────┬───────┴──────────────┘
26                                 │ (内部通信与数据存储)
27                                 ▼
28   ┌─────────────────────────────────────────────────────────────────┐
29   │ 基础设施层 (StatefulSet / Deployment)                            │
30   │ ├─ Nacos (注册/配置中心)   ├─ MySQL (数据存储)    ├─ Redis (缓存) │
31   │ ├─ Minio (对象存储)       ├─ Sentinel (流控限流)                  │
32   └─────────────────────────────────────────────────────────────────┘

环境与集群信息

主机 IP 角色
k8s-master 192.168.20.126 K8s 控制平面
k8s-node01 192.168.20.127 工作节点(运行所有业务 Pod)
k8s-node02 192.168.20.128 工作节点
docker-builder 192.168.20.125 Docker 打包机 + Harbor 仓库

所有虚拟机用户 root,密码 1。 由于使用本地 hostPath 持久化,所有有状态服务(MySQL/Redis/Nacos/Minio)通过 nodeAffinity 固定在 k8s-node01 上。


准备工作:创建本地挂载目录

在 k8s-node01(192.168.20.127)上执行:

1mkdir -p /data/k8s/ruoyi/{mysql,redis,nacos,minio/data,minio/config}
2chmod -R 777 /data/k8s/ruoyi/

创建命名空间

创建 ruoyi-env.yaml:

1apiVersion: v1
2kind: Namespace
3metadata:
4  name: ruoyi
1kubectl apply -f ruoyi-env.yaml

部署基础设施

MySQL

创建 mysql.yaml:

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-mysql
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-mysql
11  template:
12    metadata:
13      labels:
14        app: ruoyi-mysql
15    spec:
16      affinity:
17        nodeAffinity:
18          requiredDuringSchedulingIgnoredDuringExecution:
19            nodeSelectorTerms:
20            - matchExpressions:
21              - key: kubernetes.io/hostname
22                operator: In
23                values:
24                - k8s-node01
25      containers:
26      - name: mysql
27        image: mysql:8.0.33
28        env:
29        - name: MYSQL_ROOT_PASSWORD
30          value: "ruoyi123"
31        ports:
32        - containerPort: 3306
33          name: mysqlport
34        volumeMounts:
35        - name: mysql-data
36          mountPath: /var/lib/mysql
37      volumes:
38      - name: mysql-data
39        hostPath:
40          path: /data/k8s/ruoyi/mysql
41          type: Directory
42---
43apiVersion: v1
44kind: Service
45metadata:
46  name: ry-db-svc
47  namespace: ruoyi
48spec:
49  ports:
50  - port: 3306
51    targetPort: 3306
52    nodePort: 32306
53  selector:
54    app: ruoyi-mysql
55  type: NodePort

⚠️ 注意:Service 名称为 ry-db-svc,这是 Nacos 和微服务中引用的数据库地址。

1kubectl apply -f mysql.yaml

导入数据库:

使用 Navicat 等工具通过 192.168.20.127:32306 连接 MySQL(密码 ruoyi123),创建 ruoyi 数据库并导入 SQL:

1CREATE DATABASE ruoyi CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

导入若依项目 sql/ 目录下的全部 4 个 SQL 文件。

Redis

创建 redis.yaml:

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-redis
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-redis
11  template:
12    metadata:
13      labels:
14        app: ruoyi-redis
15    spec:
16      affinity:
17        nodeAffinity:
18          requiredDuringSchedulingIgnoredDuringExecution:
19            nodeSelectorTerms:
20            - matchExpressions:
21              - key: kubernetes.io/hostname
22                operator: In
23                values:
24                - k8s-node01
25      containers:
26      - name: redis
27        image: redis:7.0-alpine
28        command: ["redis-server", "--appendonly", "yes", "--requirepass", "ruoyi123"]
29        ports:
30        - containerPort: 6379
31          name: redisport
32        volumeMounts:
33        - name: redis-data
34          mountPath: /data
35      volumes:
36      - name: redis-data
37        hostPath:
38          path: /data/k8s/ruoyi/redis
39          type: Directory
40---
41apiVersion: v1
42kind: Service
43metadata:
44  name: redis-svc
45  namespace: ruoyi
46spec:
47  ports:
48  - port: 6379
49    targetPort: 6379
50  selector:
51    app: ruoyi-redis
1kubectl apply -f redis.yaml

Nacos(注册中心 + 配置中心)

创建 nacos.yaml:

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-nacos
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-nacos
11  template:
12    metadata:
13      labels:
14        app: ruoyi-nacos
15    spec:
16      affinity:
17        nodeAffinity:
18          requiredDuringSchedulingIgnoredDuringExecution:
19            nodeSelectorTerms:
20            - matchExpressions:
21              - key: kubernetes.io/hostname
22                operator: In
23                values:
24                - k8s-node01
25      containers:
26      - name: nacos
27        image: nacos/nacos-server:v3.1.2
28        env:
29        - name: MODE
30          value: "standalone"
31        - name: SPRING_DATASOURCE_PLATFORM
32          value: "mysql"
33        - name: MYSQL_SERVICE_HOST
34          value: "ry-db-svc.ruoyi.svc.cluster.local"
35        - name: MYSQL_SERVICE_PORT
36          value: "3306"
37        - name: MYSQL_SERVICE_DB_NAME
38          value: "ruoyi"
39        - name: MYSQL_SERVICE_USER
40          value: "root"
41        - name: MYSQL_SERVICE_PASSWORD
42          value: "ruoyi123"
43        - name: MYSQL_SERVICE_DB_PARAM
44          value: "characterEncoding=utf8&connectTimeout=5000&socketTimeout=5000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"
45        - name: NACOS_AUTH_ENABLE
46          value: "true"
47        - name: NACOS_AUTH_IDENTITY_KEY
48          value: "ruoyi"
49        - name: NACOS_AUTH_IDENTITY_VALUE
50          value: "ruoyi_secret"
51        - name: NACOS_AUTH_TOKEN
52          value: "SecretKey01234567890123456789012345678901234567890123456789"
53        ports:
54        - containerPort: 8080      # ======= 修改:容器内变成了 8080 =======
55          name: nacosport
56        - containerPort: 9080      # ======= 修改:gRPC 随之顺延变成 9080 =======
57          name: grpcport
58        volumeMounts:
59        - name: nacos-logs
60          mountPath: /home/nacos/logs
61      volumes:
62      - name: nacos-logs
63        hostPath:
64          path: /data/k8s/ruoyi/nacos
65          type: Directory
66---
67apiVersion: v1
68kind: Service
69metadata:
70  name: nacos-svc
71  namespace: ruoyi
72spec:
73  type: NodePort
74  selector:
75    app: ruoyi-nacos
76  ports:
77    - name: http-console   # 1. 对应你改过的网页控制台
78      port: 8080           # 微服务在集群内找 Nacos 依然用 8080 端口
79      targetPort: 8080     # ======= 核心对齐:精准命中容器内 8080 Console =======
80      nodePort: 30848      # 宿主机外网暴露端口(方便你浏览器打开 Nacos 网页)
81
82    - name: grpc-core      # 2. 对应若依微服务的 gRPC 通信
83      port: 9080           # 微服务在集群内找 gRPC 依然默认找 9080 端口
84      targetPort: 9848     # ======= 核心对齐:K8s 底层悄悄转给容器内真正的 9848 gRPC =======
85      nodePort: 31848
86
87    - name: grpc-client    # 3. 对应若依微服务的 gRPC 特权/客户端重连端口
88      port: 9081           # 微服务在集群内寻找的 9081
89      targetPort: 9849     # ======= 核心对齐:K8s 底层悄悄转给容器内真正的 9849 =======
90      nodePort: 31849
1kubectl apply -f nacos.yaml

访问控制台:http://192.168.20.127:30848/nacos/
登录账号/密码:nacos / nacos

注意:Nacos API 端口是 8848(映射为 NodePort 31884),配置管理及服务发现通过此端口通信。

Minio(对象存储)

创建 minio.yaml:

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-minio
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-minio
11  template:
12    metadata:
13      labels:
14        app: ruoyi-minio
15    spec:
16      affinity:
17        nodeAffinity:
18          requiredDuringSchedulingIgnoredDuringExecution:
19            nodeSelectorTerms:
20            - matchExpressions:
21              - key: kubernetes.io/hostname
22                operator: In
23                values:
24                - k8s-node01 # 依然锁死在 node01 节点,方便数据持久化
25      containers:
26      - name: minio
27        image: swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/quay.io/minio/minio:RELEASE.2025-06-13T11-33-47Z
28        args:
29        - server
30        - /data
31        - --console-address
32        - :9001
33        env:
34        - name: MINIO_ROOT_USER
35          value: "minioadmin"      # 默认账号
36        - name: MINIO_ROOT_PASSWORD
37          value: "minioadmin"  # 默认密码(若依微服务默认连这个,先别改)
38        ports:
39        - containerPort: 9000
40          name: api
41        - containerPort: 9001
42          name: console
43        volumeMounts:
44        - name: minio-data
45          mountPath: /data
46      volumes:
47      - name: minio-data
48        hostPath:
49          path: /data/k8s/ruoyi/minio # 宿主机挂载路径
50          type: DirectoryOrCreate
51---
52apiVersion: v1
53kind: Service
54metadata:
55  name: minio-svc
56  namespace: ruoyi
57spec:
58  ports:
59  - port: 9000
60    name: api
61    targetPort: 9000
62    nodePort: 30900 # 若依微服务代码内部通信端口
63  - port: 9001
64    name: console
65    targetPort: 9001
66    nodePort: 30901 # 外部浏览器登录建桶的端口
67  selector:
68    app: ruoyi-minio
69  type: NodePort
1kubectl apply -f minio.yaml

访问控制台:http://192.168.20.127:30901(账号:minioadmin / minioadmin)

Sentinel Dashboard(流控)

创建 sentinel.yaml:

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-sentinel
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-sentinel
11  template:
12    metadata:
13      labels:
14        app: ruoyi-sentinel
15    spec:
16      containers:
17      - name: sentinel
18        image: swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/bladex/sentinel-dashboard:latest
19        ports:
20        - containerPort: 8858
21          name: authport
22---
23apiVersion: v1
24kind: Service
25metadata:
26  name: sentinel-svc
27  namespace: ruoyi
28spec:
29  ports:
30  - port: 8858
31    targetPort: 8858
32    nodePort: 30858
33  selector:
34    app: ruoyi-sentinel
35  type: NodePort
1kubectl apply -f sentinel.yaml

访问控制台:http://192.168.20.127:30858


Nacos 配置中心设置

在所有微服务启动前,需要在 Nacos 中先创建好对应的配置。

通用配置:application-dev.yml

 1spring:
 2  autoconfigure:
 3    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure,org.springframework.boot.micrometer.metrics.autoconfigure.system.SystemMetricsAutoConfiguration
 4
 5# feign 配置
 6feign:
 7  sentinel:
 8    enabled: true
 9  okhttp:
10    enabled: true
11  httpclient:
12    enabled: false
13  client:
14    config:
15      default:
16        connectTimeout: 10000
17        readTimeout: 10000
18  compression:
19    request:
20      enabled: true
21      min-request-size: 8192
22    response:
23      enabled: true
24
25# 暴露监控端点
26management:
27  endpoints:
28    web:
29      exposure:
30        include: '*'
31  metrics:
32    binders:
33      processor:
34        enabled: false

网关配置:ruoyi-gateway-dev.yml

 1spring:
 2  data:
 3    redis:
 4      host: redis-svc.ruoyi.svc.cluster.local
 5      port: 6379
 6      password: ruoyi123
 7  redis:
 8    host: redis-svc.ruoyi.svc.cluster.local
 9    port: 6379
10    password: ruoyi123
11  cloud:
12    gateway:
13      server:
14        webflux:
15          discovery:
16            locator:
17              lowerCaseServiceId: true
18              enabled: true
19          routes:
20            # 认证中心
21            - id: ruoyi-auth
22              uri: lb://ruoyi-auth
23              predicates:
24                - Path=/auth/**
25              filters:
26                # 验证码处理
27                - name: CacheRequestBody
28                  args:
29                    bodyClass: java.lang.String
30                - ValidateCodeFilter
31                - StripPrefix=1
32            # 代码生成
33            - id: ruoyi-gen
34              uri: lb://ruoyi-gen
35              predicates:
36                - Path=/code/**
37              filters:
38                - StripPrefix=1
39            # 定时任务
40            - id: ruoyi-job
41              uri: lb://ruoyi-job
42              predicates:
43                - Path=/schedule/**
44              filters:
45                - StripPrefix=1
46            # 系统模块
47            - id: ruoyi-system
48              uri: lb://ruoyi-system
49              predicates:
50                - Path=/system/**
51              filters:
52                - StripPrefix=1
53            # 文件服务
54            - id: ruoyi-file
55              uri: lb://ruoyi-file
56              predicates:
57                - Path=/file/**
58              filters:
59                - StripPrefix=1
60
61# 安全配置
62security:
63  captcha:
64    enabled: true
65    type: math
66  xss:
67    enabled: true
68    excludeUrls:
69      - /system/notice
70  ignore:
71    whites:
72      - /auth/logout
73      - /auth/login
74      - /auth/register
75      - /*/v2/api-docs
76      - /*/v3/api-docs
77      - /csrf
78
79springdoc:
80  webjars:
81    prefix:

⚠️ 注意事项:

  1. 属性前缀:新版本 Spring Cloud Gateway(5.x)使用 spring.cloud.gateway.server.webflux 前缀,而非旧版的 spring.cloud.gateway。如果不使用正确前缀,路由配置虽然能加载到 Spring 环境中,但无法被 GatewayProperties 绑定识别,所有路由将返回 404。
  2. CacheRequestBody 参数:CacheRequestBody 过滤器必须指定 bodyClass: java.lang.String,否则启动时会报 bodyClass must not be null。

Auth 配置:ruoyi-auth-dev.yml

 1spring:
 2  data:
 3    redis:
 4      host: redis-svc.ruoyi.svc.cluster.local
 5      port: 6379
 6      password: ruoyi123
 7  redis:
 8    host: redis-svc.ruoyi.svc.cluster.local
 9    port: 6379
10    password: ruoyi123

System 配置:ruoyi-system-dev.yml

 1# spring配置
 2spring:
 3  data:
 4    redis:
 5      host: redis-svc.ruoyi.svc.cluster.local
 6      port: 6379
 7      password: ruoyi123
 8  redis:
 9    host: redis-svc.ruoyi.svc.cluster.local
10    port: 6379
11    password: ruoyi123
12  datasource:
13    druid:
14      stat-view-servlet:
15        enabled: true
16        loginUsername: ruoyi
17        loginPassword: 123456
18    dynamic:
19      druid:
20        initial-size: 5
21        min-idle: 5
22        maxActive: 20
23        maxWait: 60000
24        connectTimeout: 30000
25        socketTimeout: 60000
26        timeBetweenEvictionRunsMillis: 60000
27        minEvictableIdleTimeMillis: 300000
28        validationQuery: SELECT 1 FROM DUAL
29        testWhileIdle: true
30        testOnBorrow: false
31        testOnReturn: false
32        poolPreparedStatements: true
33        maxPoolPreparedStatementPerConnectionSize: 20
34        filters: stat,slf4j
35        connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
36      datasource:
37          # 主库数据源
38          master:
39            driver-class-name: com.mysql.cj.jdbc.Driver
40            url: jdbc:mysql://ry-db-svc.ruoyi.svc.cluster.local:3306/ruoyi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
41            username: root
42            password: ruoyi123
43          # 从库数据源
44          # slave:
45            # username: 
46            # password: 
47            # url: 
48            # driver-class-name: 
49
50# mybatis配置
51mybatis:
52    # 搜索指定包别名
53    typeAliasesPackage: com.ruoyi.system
54    # 配置mapper的扫描,找到所有的mapper.xml映射文件
55    mapperLocations: classpath*:mapper/**/*.xml
56
57# springdoc配置
58springdoc:
59  gatewayUrl: http://192.168.20.127:30080/${spring.application.name}
60  api-docs:
61    # 是否开启接口文档
62    enabled: true
63  info:
64    # 标题
65    title: '系统模块接口文档'
66    # 描述
67    description: '系统模块接口描述'
68    # 作者信息
69    contact:
70      name: RuoYi
71      url: https://ruoyi.vip

Gen配置:ruoyi-gen-dev.yml

 1# spring配置
 2spring:
 3  data:
 4    redis:
 5      host: redis-svc.ruoyi.svc.cluster.local
 6      port: 6379
 7      password: ruoyi123
 8  redis:
 9    host: redis-svc.ruoyi.svc.cluster.local
10    port: 6379
11    password: ruoyi123
12  datasource:
13    driver-class-name: com.mysql.cj.jdbc.Driver
14    url: jdbc:mysql://ry-db-svc.ruoyi.svc.cluster.local:3306/ruoyi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
15    username: root
16    password: ruoyi123
17
18# mybatis配置
19mybatis:
20    # 搜索指定包别名
21    typeAliasesPackage: com.ruoyi.gen.domain
22    # 配置mapper的扫描,找到所有的mapper.xml映射文件
23    mapperLocations: classpath*:mapper/**/*.xml
24
25# springdoc配置
26springdoc:
27  gatewayUrl: http://192.168.20.127:30080/${spring.application.name}
28  api-docs:
29    # 是否开启接口文档
30    enabled: true
31  info:
32    # 标题
33    title: '代码生成接口文档'
34    # 描述
35    description: '代码生成接口描述'
36    # 作者信息
37    contact:
38      name: RuoYi
39      url: https://ruoyi.vip
40
41# 代码生成
42gen:
43  # 作者
44  author: ruoyi
45  # 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool
46  packageName: com.ruoyi.system
47  # 自动去除表前缀,默认是false
48  autoRemovePre: false
49  # 表前缀(生成类名不会包含表前缀,多个用逗号分隔)
50  tablePrefix: sys_
51  # 是否允许生成文件覆盖到本地(自定义路径),默认不允许
52  allowOverwrite: false

Job配置:ruoyi-job-dev.yml

 1# spring配置
 2spring:
 3  data:
 4    redis:
 5      host: redis-svc.ruoyi.svc.cluster.local
 6      port: 6379
 7      password: ruoyi123
 8  redis:
 9    host: redis-svc.ruoyi.svc.cluster.local
10    port: 6379
11    password: ruoyi123
12  datasource:
13    driver-class-name: com.mysql.cj.jdbc.Driver
14    url: jdbc:mysql://ry-db-svc.ruoyi.svc.cluster.local:3306/ruoyi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
15    username: root
16    password: ruoyi123
17
18# mybatis配置
19mybatis:
20    # 搜索指定包别名
21    typeAliasesPackage: com.ruoyi.job.domain
22    # 配置mapper的扫描,找到所有的mapper.xml映射文件
23    mapperLocations: classpath*:mapper/**/*.xml
24
25# springdoc配置
26springdoc:
27  gatewayUrl: http://192.168.20.127:30080/${spring.application.name}
28  api-docs:
29    # 是否开启接口文档
30    enabled: true
31  info:
32    # 标题
33    title: '定时任务接口文档'
34    # 描述
35    description: '定时任务接口描述'
36    # 作者信息
37    contact:
38      name: RuoYi
39      url: https://ruoyi.vip

File 配置:ruoyi-file-dev.yml

 1# 本地文件上传    
 2file:
 3    domain: http://127.0.0.1:9300
 4    path: D:/ruoyi/uploadPath
 5    prefix: /statics
 6
 7# FastDFS配置
 8fdfs:
 9  domain: http://127.0.0.1
10  soTimeout: 3000
11  connectTimeout: 2000
12  trackerList: 127.0.0.1:22122
13
14# Minio配置
15minio:
16  url: http://minio-svc.ruoyi.svc.cluster.local:9000
17  accessKey: minioadmin
18  secretKey: minioadmin
19  bucketName: ruoyi
20
21  # 防盗链配置
22referer:
23  # 防盗链开关
24  enabled: false
25  # 允许的域名列表
26  allowed-domains: localhost,127.0.0.1,ruoyi.vip,www.ruoyi.vip

修改引导配置(源码级)

在 Docker 打包机上,修改各模块的 bootstrap.yml,使它们指向 K8s 集群内的 Nacos。

Gateway

1vi /data/ruoyi/RuoYi-Cloud-master/ruoyi-gateway/src/main/resources/bootstrap.yml
 1# Tomcat
 2server:
 3  port: 8080
 4
 5# Spring
 6spring:
 7  application:
 8    # 应用名称
 9    name: ruoyi-gateway
10  profiles:
11    # 环境配置
12    active: dev
13  cloud:
14    nacos:
15      # ====== 核心修改 1:补充 Nacos 3.x 鉴权账号密码 ======
16      username: nacos
17      password: nacos
18      discovery:
19        # 服务注册地址
20        server-addr: nacos-svc.ruoyi.svc.cluster.local:8848
21      config:
22        # 配置中心地址
23        server-addr: nacos-svc.ruoyi.svc.cluster.local:8848
24    sentinel:
25      # 取消控制台懒加载
26      eager: true
27      transport:
28        # ====== 核心修改 2:指向未来你在 K8s 内部署的 Sentinel 服务域名与端口 ======
29        # 假设你后面为 Sentinel 控制台创建的 Service 叫 sentinel-svc
30        dashboard: sentinel-svc.ruoyi.svc.cluster.local:8718
31      # nacos配置持久化
32      datasource:
33        ds1:
34          nacos:
35            # ====== 核心修改 3:对齐 K8s 内部的 Nacos 地址与端口 ======
36            server-addr: nacos-svc.ruoyi.svc.cluster.local:8848
37            # ====== 核心修改 4:Sentinel 访问 Nacos 也必须带上账号密码 ======
38            username: nacos
39            password: nacos
40            dataId: sentinel-ruoyi-gateway
41            groupId: DEFAULT_GROUP
42            data-type: json
43            rule-type: gw-flow
44  config:
45    # 配置文件格式
46    file-extension: yml
47    import:
48      - nacos:application-${spring.profiles.active}.${spring.config.file-extension}
49      - nacos:${spring.application.name}-${spring.profiles.active}.${spring.config.file-extension}

Auth / System / Job / Gen / File

这些模块的 bootstrap.yml 结构相同,仅 server.port 和 spring.application.name 不同:

模块 server.port
auth 9200
system 9201
job 9203
gen 9202
file 9300

模板:

 1# Tomcat
 2server:
 3  port: <对应端口>
 4
 5# Spring
 6spring:
 7  application:
 8    # 应用名称
 9    name: <对应模块名>
10  profiles:
11    # 环境配置
12    active: dev
13  cloud:
14    nacos:
15      # ====== 核心修改 1:补充 Nacos 3.x 鉴权账号密码 ======
16      username: nacos
17      password: nacos
18      discovery:
19        # ====== 核心修改 2:服务注册地址对齐 K8s 内部域名与端口 ======
20        server-addr: nacos-svc.ruoyi.svc.cluster.local:8848
21      config:
22        # ====== 核心修改 3:配置中心地址对齐 K8s 内部域名与端口 ======
23        server-addr: nacos-svc.ruoyi.svc.cluster.local:8848
24  config:
25    # 配置文件格式
26    file-extension: yml
27    import:
28      - nacos:application-${spring.profiles.active}.${spring.config.file-extension}
29      - nacos:${spring.application.name}-${spring.profiles.active}.${spring.config.file-extension}

File 模块额外修改

由于 file 模块同时依赖 Local 和 Minio 实现,需要将 Minio 设为默认实现:

1vi /data/ruoyi/RuoYi-Cloud-master/ruoyi-modules/ruoyi-file/src/main/java/com/ruoyi/file/service/MinioSysFileServiceImpl.java

在类上添加 @Primary 注解:

1import org.springframework.context.annotation.Primary;
2
3@Primary  // <-- 添加此行,优先使用 Minio
4@Service
5public class MinioSysFileServiceImpl implements ISysFileService {
6    ...
7}

关闭文件上传到本地

1vim ruoyi-modules/ruoyi-file/src/main/java/com/ruoyi/file/service/LocalSysFileServiceImpl.java
1// @Primary  // <-- 注释此行
2@Service
3public class LocalSysFileServiceImpl implements ISysFileService {
4    ...
5}

Docker 镜像构建与推送

Dockerfile

在每个微服务模块目录下创建 Dockerfile:

 1FROM openjdk:17-jdk-alpine
 2
 3RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' > /etc/timezone
 4
 5WORKDIR /app
 6VOLUME /tmp
 7
 8COPY target/*.jar app.jar
 9
10EXPOSE 8080
11
12ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar", "--spring.profiles.active=dev"]

构建与推送脚本

 1#!/bin/bash
 2
 3set -e
 4
 5# Harbor 仓库地址
 6REGISTRY="www.chenyang-helloworld.top/ruoyi"
 7TAG="v1.0.0"
 8
 9# 需要打包的模块 (目录:镜像名)
10MODULES=(
11  "ruoyi-gateway:ruoyi-gateway"
12  "ruoyi-auth:ruoyi-auth"
13  "ruoyi-modules/ruoyi-system:ruoyi-system"
14  "ruoyi-modules/ruoyi-job:ruoyi-job"
15  "ruoyi-modules/ruoyi-gen:ruoyi-gen"
16  "ruoyi-modules/ruoyi-file:ruoyi-file"
17)
18
19echo "============ Maven 编译打包 ============"
20mvn clean package -DskipTests
21
22echo "============ 构建 & 推送 Docker 镜像 ============"
23for item in "${MODULES[@]}"; do
24    DIR_PATH="${item%%:*}"
25    IMAGE_NAME="${item##*:}"
26
27    echo ">>> 处理: ${IMAGE_NAME} (${DIR_PATH})"
28
29    cd ${DIR_PATH}
30    docker build -t ${IMAGE_NAME}:${TAG} .
31    docker tag ${IMAGE_NAME}:${TAG} ${REGISTRY}/${IMAGE_NAME}:${TAG}
32    docker push ${REGISTRY}/${IMAGE_NAME}:${TAG}
33    docker rmi ${REGISTRY}/${IMAGE_NAME}:${TAG}
34    cd - > /dev/null
35done
36
37echo "============ 全部完成 ============"

K8s 部署编排

网关:ruoyi-gateway.yaml

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-gateway
 5  namespace: ruoyi
 6  labels:
 7    app: ruoyi-gateway
 8spec:
 9  replicas: 1
10  selector:
11    matchLabels:
12      app: ruoyi-gateway
13  template:
14    metadata:
15      labels:
16        app: ruoyi-gateway
17    spec:
18      imagePullSecrets:
19        - name: harbor-secret
20      containers:
21        - name: ruoyi-gateway
22          image: www.chenyang-helloworld.top/ruoyi/ruoyi-gateway:v1.0.0
23          imagePullPolicy: Always
24          ports:
25            - containerPort: 8080
26          env:
27            - name: JAVA_OPTS
28              value: "-XX:-UseContainerSupport -Xms256m -Xmx512m"
29
30---
31apiVersion: v1
32kind: Service
33metadata:
34  name: ruoyi-gateway
35  namespace: ruoyi
36  labels:
37    app: ruoyi-gateway
38spec:
39  type: ClusterIP
40  ports:
41    - port: 8080
42      targetPort: 8080
43  selector:
44    app: ruoyi-gateway

认证模块:ruoyi-auth.yaml

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-auth
 5  namespace: ruoyi
 6  labels:
 7    app: ruoyi-auth
 8spec:
 9  replicas: 1
10  selector:
11    matchLabels:
12      app: ruoyi-auth
13  template:
14    metadata:
15      labels:
16        app: ruoyi-auth
17    spec:
18      imagePullSecrets:
19        - name: harbor-secret
20      containers:
21        - name: ruoyi-auth
22          image: www.chenyang-helloworld.top/ruoyi/ruoyi-auth:v1.0.0
23          imagePullPolicy: Always
24          ports:
25            - containerPort: 9218
26          env:
27            - name: JAVA_OPTS
28              value: "-XX:-UseContainerSupport -Xms256m -Xmx512m"
29---
30apiVersion: v1
31kind: Service
32metadata:
33  name: ruoyi-auth
34  namespace: ruoyi
35  labels:
36    app: ruoyi-auth
37spec:
38  type: ClusterIP
39  ports:
40    - port: 9218
41      targetPort: 9218
42  selector:
43    app: ruoyi-auth

系统核心模块:ruoyi-system.yaml

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-system
 5  namespace: ruoyi
 6  labels:
 7    app: ruoyi-system
 8spec:
 9  replicas: 1
10  selector:
11    matchLabels:
12      app: ruoyi-system
13  template:
14    metadata:
15      labels:
16        app: ruoyi-system
17    spec:
18      imagePullSecrets:
19        - name: harbor-secret
20      containers:
21        - name: ruoyi-system
22          image: www.chenyang-helloworld.top/ruoyi/ruoyi-system:v1.0.0
23          imagePullPolicy: Always
24          ports:
25            - containerPort: 9201
26          env:
27            - name: JAVA_OPTS
28              value: "-XX:-UseContainerSupport -Xms256m -Xmx512m"
29---
30apiVersion: v1
31kind: Service
32metadata:
33  name: ruoyi-system
34  namespace: ruoyi
35  labels:
36    app: ruoyi-system
37spec:
38  type: ClusterIP
39  ports:
40    - port: 9201
41      targetPort: 9201
42  selector:
43    app: ruoyi-system

其他模块:job / gen / file

ruoyi-job.yaml(端口 9203)、ruoyi-gen.yaml(端口 9202)、ruoyi-file.yaml(端口 9300)

模板参考 system 模块,调整端口、服务名和镜像名即可。

前端 UI:ruoyi-ui.yaml

 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: ruoyi-ui	
 5  namespace: ruoyi
 6spec:
 7  replicas: 1
 8  selector:
 9    matchLabels:
10      app: ruoyi-ui
11  template:
12    metadata:
13      labels:
14        app: ruoyi-ui
15    spec:
16      nodeSelector:
17        kubernetes.io/hostname: k8s-node01
18      containers:
19      - name: nginx
20        image: nginx:1.25-alpine
21        ports:
22        - containerPort: 80
23        volumeMounts:
24        - name: dist
25          mountPath: /usr/share/nginx/html
26          readOnly: true
27        - name: nginx-conf
28          mountPath: /etc/nginx/conf.d/default.conf
29          readOnly: true
30          subPath: default.conf
31      volumes:
32      - name: dist
33        hostPath:
34          path: /data/k8s/ruoyi/ui/dist
35          type: Directory
36      - name: nginx-conf
37        configMap:
38          name: ruoyi-ui-nginx-conf
39---
40apiVersion: v1
41kind: Service
42metadata:
43  name: ruoyi-ui
44  namespace: ruoyi
45spec:
46  type: NodePort
47  ports:
48  - port: 80
49    targetPort: 80
50    nodePort: 30081
51  selector:
52    app: ruoyi-ui

Nginx ConfigMap:ruoyi-ui-nginx-conf

 1apiVersion: v1
 2kind: ConfigMap
 3metadata:
 4  name: ruoyi-ui-nginx-conf
 5  namespace: ruoyi
 6data:
 7  default.conf: |
 8    server {
 9      listen 80;
10      server_name _;
11      charset utf-8;
12      root /usr/share/nginx/html;
13      index index.html index.htm;
14      client_max_body_size 100m;
15
16      location / {
17        try_files $uri $uri/ /index.html;
18      }
19
20      location /prod-api/ {
21        proxy_set_header Host $host;
22        proxy_set_header X-Real-IP $remote_addr;
23        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
24        proxy_set_header X-Forwarded-Proto $scheme;
25        proxy_pass http://ruoyi-gateway.ruoyi.svc.cluster.local:8080/;
26      }
27    }

前端 baseURL 在 Vue 构建时配置为 /prod-api,Nginx 将匹配到的 /prod-api/ 请求反向代理到网关服务。

一键部署

1kubectl apply -f ruoyi-system.yaml
2kubectl apply -f ruoyi-auth.yaml
3kubectl apply -f ruoyi-gateway.yaml
4kubectl apply -f ruoyi-job.yaml
5kubectl apply -f ruoyi-gen.yaml
6kubectl apply -f ruoyi-file.yaml
7kubectl apply -f ruoyi-ui.yaml

服务访问汇总

服务 访问地址 说明
前端登录页 http://192.168.20.127:30081 若依管理界面
网关 http://192.168.20.127:30080 Gateway API 入口
Nacos 控制台 http://192.168.20.127:30848/nacos/ 注册中心 & 配置中心(nacos/nacos)
Sentinel http://192.168.20.127:30858 流控控制台
Minio Console http://192.168.20.127:30901 管理后台(minioadmin/minioadmin)
MySQL 192.168.20.127:32306 数据库(root/ruoyi123)

常见问题排查

登录时报 404 “No static resource auth/login”

原因:Gateway 的 spring.cloud.gateway.* 路由配置属性前缀不匹配。

新版本 Spring Cloud Gateway(5.x)使用 spring.cloud.gateway.server.webflux 作为配置前缀,而非旧版的 spring.cloud.gateway。

修复:在 Nacos 中将配置前缀改为新版本格式,然后重启 gateway:

1kubectl rollout restart -n ruoyi deploy/ruoyi-gateway

Gateway 报 “bodyClass must not be null”

原因:CacheRequestBody 过滤器缺少 bodyClass 参数。

修复:将 - CacheRequestBody 改为带参数的形式:

1filters:
2  - name: CacheRequestBody
3    args:
4      bodyClass: java.lang.String

验证 Gateway 路由

1# 测试验证码接口
2curl http://192.168.20.127:30080/code
3
4# 测试登录接口
5curl -X POST http://192.168.20.127:30080/auth/login \
6  -H "Content-Type: application/json" \
7  -d '{"username":"admin","password":"admin123"}'

查看各服务日志

1# 网关
2kubectl logs -n ruoyi deploy/ruoyi-gateway -f
3
4# Auth
5kubectl logs -n ruoyi deploy/ruoyi-auth -f
6
7# 查看 gateway 健康状态
8kubectl exec -n ruoyi deploy/ruoyi-gateway -- \
9  wget -q -O - http://127.0.0.1:8080/actuator/health

注意事项

  1. 镜像拉取密钥:从私有 Harbor 拉取镜像需要创建 harbor-secret:

    1kubectl create secret docker-registry harbor-secret \
    2  -n ruoyi \
    3  --docker-server=www.chenyang-helloworld.top \
    4  --docker-username=<你的Harbor账号> \
    5  --docker-password=<你的Harbor密码>
    
  2. 节点绑定:所有有状态服务(MySQL/Redis/Nacos/Minio)通过 nodeSelector 绑定到 k8s-node01,确保数据持久化不漂移。

  3. Nacos 配置更新:修改 Nacos 中的配置后,对应服务需要重启才能生效。

  4. Auth 服务不需要数据库:auth 模块排除了 DataSourceAutoConfiguration,只做认证逻辑。

  5. 健康检查:建议为每个 Deployment 添加 livenessProbe 和 readinessProbe,确保 K8s 能正确处理 Pod 异常。

Wuwei’s Blog
记录技术与生活