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

Vite+Vue应用Docker容器文件监听失效,开启usePolling后崩溃求助

解决Docker容器中Vite+Vue的文件监听与容器关闭问题

核心解决方案

针对文件监听失效和开启usePolling后容器无法关闭的问题,从Vite配置、Docker配置两个层面调整:

1. 优化Vite的文件监听配置

修改vite.config.js的server.watch选项,在开启轮询的同时限制轮询范围、降低频率,并启用只读轮询减少资源占用:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [vue()],
    build: {
        assetsDir: '.',
        assetsInlineLimit: 0,
        assetsInclude: ['**/*'], 
        rollupOptions: {
            input: {
                main: 'src/main.js',
            },
            output: {
                entryFileNames: 'main.js',
                chunkFileNames: '[name].js',
                assetFileNames: '[name].[ext]', 
            },
        },
    },
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    server: {
        port: 3000,
        host: true,
        strictPort: true,
        watch: {
            usePolling: true,
            useReadOnlyPolling: true, // 避免不必要的文件写操作,降低资源消耗
            pollInterval: 1000, // 调整轮询间隔,降低频率减少CPU占用
            ignored: ['**/node_modules/**', '**/.git/**'] // 忽略无需监听的目录
        }
    }
})

2. 调整Docker配置确保信号传递

修改docker-compose.yml

添加卷挂载的delegated模式优化文件同步,同时确保容器能正确接收终止信号:

version: '3.8'

services:
  node:
    build:
      context: .
    container_name: app-js
    ports:
      - "3035:3000"
    volumes:
      - ./:/usr/src/app:delegated # 提升宿主机与容器的文件同步效率
    init: true
    stop_signal: SIGINT # 指定终止信号,确保Vite进程能正确接收并退出
    tty: true # 分配伪终端,帮助信号传递

修改package.json的dev脚本

让Vite进程直接作为PID 1运行,确保终止信号能被正确捕获:

{
  "scripts": {
    "dev": "exec vite"
  }
}

问题原因分析

  • 文件监听失效:Docker容器内默认的inotify机制无法感知宿主机的文件变化,必须开启usePolling通过轮询检测文件改动。
  • 容器无法关闭:开启轮询后,Vite会创建多个子进程处理文件监听,如果信号无法传递到这些进程(比如npm作为PID 1时会拦截信号),进程无法正常终止,导致容器僵死甚至Docker崩溃。通过exec vite让Vite成为PID 1,配合stop_signal: SIGINT确保终止信号能被处理;useReadOnlyPolling和ignored则减少轮询带来的资源消耗,避免Docker因资源过载崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:57:40