如何修复 Docker 在 Angular 15 中陷入“RUN npm run build”的问题

Kev*_*ach 5 node.js npm docker angular

我正在尝试在 Docker 中构建 Angular 15 项目,但构建总是挂在该RUN npm run build步骤上并且永远不会完成。这是一个全新安装ng new ng-sandbox-15Dockerfile并且.dockerignorenginx.conf工作中的 Angular 14 全新安装复制而来。

./Dockerfile

FROM node:16-alpine as builder

# Copy dependency definitions
COPY package.json package-lock.json ./

# disabling ssl for npm for Dev or if you are behind proxy
RUN npm set strict-ssl false

## installing and Storing node modules on a separate layer will prevent unnecessary npm installs at each build
RUN npm ci && mkdir /app && mv ./node_modules ./app

# Change directory so that our commands run inside this new directory
WORKDIR /app

# Get all the code needed to run the app
COPY . /app/

# Build the application
RUN npm run build


FROM nginx:1.17-alpine
## From 'builder' copy published folder
COPY --from=builder /app/dist /usr/share/nginx/html

COPY nginx/nginx.conf /etc/nginx/nginx.conf

# Expose the port the app runs in
EXPOSE 4000

CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)

./package.json:

{
  "name": "ng-sandbox-15",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.2.0",
    "@angular/common": "^15.2.0",
    "@angular/compiler": "^15.2.0",
    "@angular/core": "^15.2.0",
    "@angular/forms": "^15.2.0",
    "@angular/platform-browser": "^15.2.0",
    "@angular/platform-browser-dynamic": "^15.2.0",
    "@angular/router": "^15.2.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.2.5",
    "@angular/cli": "~15.2.5",
    "@angular/compiler-cli": "^15.2.0",
    "@types/jasmine": "~4.3.0",
    "jasmine-core": "~4.5.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.9.4"
  }
}
Run Code Online (Sandbox Code Playgroud)

如下图所示,Angular 构建在 26.5 秒内成功完成,但该步骤在 20 多分钟后仍然卡住。

Docker 卡在 RUN npm run build 上

我见过的最相似的问题是Docker build 陷入 npm run build step,我不同意唯一提出的答案CMD ["npm", "run", "build"],因为在尝试将构建的项目复制到 nginx html 目录之前,它不会等待构建完成。

小智 3

当我将 Angular 13 项目更新到 15 时,我遇到了同样的问题。

我有 4 个项目,2 个将构建成功,2 个将在RUN npm run build. 比较项目后,我发现我的案例是由角度构建内部的分析引起的。

更改参数angular.json来自

"cli": {
  "analytics": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX",
},
Run Code Online (Sandbox Code Playgroud)

"cli": {
  "analytics": false,
},
Run Code Online (Sandbox Code Playgroud)

这个解决方案解决了我的问题。根本原因可能是上传分析数据被阻止在 docker build 内