Angular(Tailwind)+Docker访问localhost:4200返回ERR_EMPTY_RESPONSE排查
我使用Angular(集成Tailwind)和Docker进行开发,但访问localhost:4200时始终收到ERR_EMPTY_RESPONSE错误。怀疑路径或node_modules位置存在问题,曾尝试添加CMD ["npm","start","--host 0.0.0.0"]但未解决。以下是我的配置文件:
Dockerfile
# pull official base image FROM node:14 ENV PATH=$PATH:app/node_modules/.bin #app/ # set working directory WORKDIR /app # install app dependencies COPY package.json ./ COPY package-lock.json ./ RUN npm install # add app #COPY . . # start app EXPOSE 4200 CMD ["npm","start"]
docker-compose.yml
version: "3.7" services: app: container_name: template restart: always build: context: . dockerfile: Dockerfile ports: - "4200:4200" volumes: - ./:/app
package.json(部分内容)
"name": "notus-angular", "version": "1.1.0", "description": "Notus Angular - Free Tailwind CSS UI Kit and Admin by Creative Tim.", "repository": "https://github.com/creativetimofficial/notus-angular", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve --host 0.0.0.0 --poll 1000 ", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "build:tailwind": "tailwind build src/assets/styles/index.css -o src/assets/styles/tailwind.css", "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm run build:tailwind && npm start" },
修复PATH环境变量错误:Dockerfile中
ENV PATH=$PATH:app/node_modules/.bin的路径缺少根目录斜杠,应改为绝对路径ENV PATH=$PATH:/app/node_modules/.bin,否则系统无法正确找到Angular CLI的执行文件。取消应用源码复制的注释:Dockerfile中
#COPY . .被注释,导致容器构建时未复制应用源码。虽然docker-compose挂载了本地目录,但取消该注释能确保构建过程中应用文件存在,避免挂载异常时的问题。修改后该部分为:# add app COPY . .避免node_modules目录冲突:docker-compose将本地目录挂载到容器的
/app,会覆盖容器内安装的node_modules(本地与容器环境可能存在差异,导致依赖无法正常运行)。需在volumes中添加匿名卷保留容器内的node_modules:volumes: - ./:/app - /app/node_modules确认服务监听地址配置:package.json的
start命令已正确添加--host 0.0.0.0,这部分无需修改。之前直接在CMD中添加参数的方式无效,因为npm start会优先执行scripts中定义的命令,单独添加的参数会被忽略。
修改完成后,执行以下命令重启服务:
docker-compose down docker-compose build --no-cache docker-compose up
内容的提问来源于stack exchange,提问作者User-rooky

