首页 > 解决方案 > 如何构建仅用于生产的 angular 9 docker 映像

问题描述

我不太喜欢前端开发。我正在为 Angular 9 应用程序构建一个 docker 映像。这是我尝试过的东西。

ARG NODE_VERSION=12.16.1

# stage - # 1
FROM node:${NODE_VERSION}-buster-slim as builder

WORKDIR /app

COPY . .

RUN npm install --only=production && npm run build --prod

# stage - #final
FROM nginx:stable

COPY --from=builder /webapp/dist/webapp /usr/share/nginx/html
COPY demo-nginx.conf /etc/nginx/nginx.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

我收到以下错误。

#10 5.883 > webapp@0.0.0 build /webapp
#10 5.883 > ng build
#10 5.883 
#10 5.885 sh: 1: ng: not found
#10 5.887 npm ERR! code ELIFECYCLE
#10 5.887 npm ERR! syscall spawn
#10 5.887 npm ERR! file sh
#10 5.887 npm ERR! errno ENOENT
#10 5.888 npm ERR! webapp@0.0.0 build: `ng build`
#10 5.888 npm ERR! spawn ENOENT
#10 5.888 npm ERR! 
#10 5.888 npm ERR! Failed at the webapp@0.0.0 build script.
#10 5.888 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#10 5.892 

当我进行生产时,只有npm install“ng”命令没有安装到图像的第一阶段。如果我不与 --only=production 一起使用,那么所有开发依赖项都将与它一起安装。我怎样才能只获得生产唯一依赖项,但为生产构建它?该npm run build --prod命令是否创建一个仅包含生产文件的 /dist 文件夹?如何正确地做到这一点?

标签: node.jsangulardockernpm

解决方案


这是工作文件:

ARG NODE_VERSION=12.16.1

# stage - # 1
FROM node:${NODE_VERSION}-buster-slim as builder

WORKDIR /app

COPY . .

RUN npm install 
RUN npm run build --prod

# stage - #final
FROM nginx:stable

COPY --from=builder /app/dist/{add_angularapp_name}  /usr/share/nginx/html

CMD ["nginx", "-g", "daemon off;"]

推荐阅读