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

Docker构建nginx服务失败:ng命令未找到问题求助

解决Docker构建前端项目时ng: not found的问题

问题场景

使用以下Dockerfile构建前端项目时,出现ng: not found错误:

## Build
FROM node:16.14-slim as build
WORKDIR /usr/src/app
COPY yarn.lock ./
RUN yarn
RUN yarn install
COPY . .
RUN npm run build

## Run
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/app/dist/frontend-app /usr/share/nginx/html

报错信息:

=> [build 3/7] COPY yarn.lock ./                                                                                  0.0s
 => [build 4/7] RUN yarn                                                                                           0.7s
 => [build 5/7] RUN yarn install                                                                                   0.7s
 => [build 6/7] COPY . .                                                                                           0.0s
 => ERROR [build 7/7] RUN npm run build                                                                            1.0s
------
 > [build 7/7] RUN npm run build:
#14 0.961
#14 0.961 > frontend-app@1.0.0 build
#14 0.961 > ng build --configuration production
#14 0.961
#14 0.966 sh: 1: ng: not found
------
executor failed running [/bin/sh -c npm run build]: exit code: 127
ERROR: Service 'nginx' failed to build : Build failed

解决建议

  • 统一包管理器,避免npm和yarn混用
    当前Dockerfile同时使用yarn安装依赖、npm执行构建,容易导致依赖环境不一致。建议全程使用同一包管理器:

    1. 移除重复的RUN yarn命令(yarn默认执行install操作)
    2. 同时复制package.json和yarn.lock以利用Docker缓存机制
    3. 将RUN npm run build改为RUN yarn build

    修改后的Build阶段:

    ## Build
    FROM node:16.14-slim as build
    WORKDIR /usr/src/app
    COPY package.json yarn.lock ./
    RUN yarn install
    COPY . .
    RUN yarn build
    
  • 确保Angular CLI可被正确调用
    找不到ng是因为环境中未安装Angular CLI,有两种解决方式:

    1. 全局安装CLI:在Build阶段添加全局安装命令(根据包管理器选择)
      # 使用yarn全局安装
      RUN yarn global add @angular/cli
      # 或使用npm全局安装
      RUN npm install -g @angular/cli
      
    2. 调用项目本地CLI:修改package.json中的build脚本,使用本地node_modules中的ng
      // npm项目
      "scripts": {
        "build": "npx ng build --configuration production"
      }
      // yarn项目
      "scripts": {
        "build": "yarn ng build --configuration production"
      }
      
  • 检查项目依赖是否包含@angular/cli
    确认package.json的devDependencies中存在@angular/cli,如果没有,先在本地项目执行安装命令,再提交修改后的package.json:

    # npm
    npm install --save-dev @angular/cli
    # yarn
    yarn add --dev @angular/cli
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:40:29