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

Docker中运行Vue测试遇pm2启动Vue开发服务器失败求助

问题解决:PM2启动Vue开发服务失败与容器内测试连接配置

问题背景

Docker环境下,通过PM2启动Vue开发服务器后无法正常提供服务,导致Cucumber测试失败,但直接运行vue-cli-service serve可正常访问http://localhost:8080。相关配置如下:

Dockerfile

FROM node:19-bullseye-slim

WORKDIR /app
# Install prerequisites
RUN apt-get update && apt-get install -y \
gnupg \
curl \
bash 

COPY . /app

CMD ./bootstrap.sh

bootstrap.sh脚本

#!/bin/bash

npm add yarn 
yarn add pm2 --dev
yarn install
npx playwright install-deps chromium
yarn test
echo "Finished"

package.json测试命令

"test": "pm2 start server.js && npm run test:cucumber",
 "test:cucumber": "cucumber-js --require ./cucumber.js --require ./tests/e2e-playwright/step-definitions/**/*.js -f json:cucumber_report.json --publish-quiet",

server.js配置

module.exports  = {
    apps: [
      {
        name: "WEB",
        script: "./node_modules/@vue/cli-service/bin/vue-cli-service.js",
        args: "serve"
      }
    ]
};

解决方案

一、让PM2启动的Vue开发服务器正常可用

核心问题是PM2启动服务后测试立刻执行,但此时Vue服务尚未完全就绪,同时需要确保服务绑定正确地址:

  1. 修改server.js,绑定全网卡地址并开启日志
    默认vue-cli-service serve仅绑定localhost,在容器内建议绑定0.0.0.0确保容器内部可访问,同时添加日志方便排查启动问题:
module.exports  = {
    apps: [
      {
        name: "WEB",
        script: "./node_modules/@vue/cli-service/bin/vue-cli-service.js",
        args: "serve --host 0.0.0.0", // 绑定所有网卡地址
        output: "./pm2-out.log", // 输出标准日志
        error: "./pm2-error.log", // 输出错误日志
        merge_logs: true
      }
    ]
};
  1. 添加服务就绪等待逻辑
    pm2 start server.js仅启动进程,不代表Vue服务已就绪。使用wait-on工具检测服务端口,确认可用后再执行测试:
  • 在bootstrap.sh中添加依赖安装:
    yarn add wait-on --dev
    
  • 修改package.json的test命令:
    "test": "pm2 start server.js && wait-on http://localhost:8080 && npm run test:cucumber",
    
  1. 可选:使用非root用户运行(提升安全性)
    在Dockerfile中添加非root用户配置,避免用root权限运行服务:
RUN useradd -m appuser
USER appuser

二、测试的连接地址配置

测试(Playwright + Cucumber)在容器内部运行,直接连接http://localhost:8080即可,无需使用host.docker.internal(该地址用于容器访问宿主机服务)。

确保测试代码中的访问地址硬编码为http://localhost:8080,比如Cucumber步骤定义里的请求地址。

额外排查点

  • 检查端口占用:在bootstrap.sh中添加apt-get install -y net-tools && netstat -tulpn | grep 8080,确认8080端口是否被其他进程占用
  • 查看PM2日志:执行pm2 logs WEB或查看pm2-out.log、pm2-error.log,排查Vue服务启动时的报错信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:47:12