Angular升级至18后Docker容器无法运行应用问题排查
问题:Angular 18升级后Docker部署显示Nginx默认页面
场景说明
- Angular从16版本升级至18版本,构建工具改用
@angular-devkit/build-angular:application(原使用browser构建器) - angular.json中outputPath配置为
dist/my-app-client - 运行Docker容器后,访问主机仅显示Nginx默认页面,而非目标应用
现有配置文件
Dockerfile
FROM node:18.20-alpine3.19 As build WORKDIR /usr/local/app COPY package*.json ./ RUN npm install COPY ./ /usr/local/app/ ARG ENVIRONMENT=production # Extract commit ID ARG COMMIT_ID RUN echo "Commit ID: $COMMIT_ID" > commit.txt RUN echo 'Environment:' ${ENVIRONMENT} RUN npm run build -- --configuration=${ENVIRONMENT} ### STAGE 2: Run ### FROM nginx:1.25.3-alpine COPY --from=build /usr/local/app/dist/my-app-client /usr/share/nginx/html COPY --from=build /usr/local/app/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /usr/local/app/commit.txt /usr/share/nginx/html EXPOSE 80
nginx.conf
server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html =404; } }
问题原因
Angular 18的application构建器与旧版browser构建器的产物目录结构不同:
- 旧
browser构建器直接将静态文件输出到outputPath根目录 - 新
application构建器会在outputPath下生成对应环境名称的子目录(例如production环境下为dist/my-app-client/production),静态文件实际存放在该子目录中。
Dockerfile中COPY的路径指向了outputPath根目录,而非实际存放静态文件的环境子目录,导致Nginx加载不到应用文件,只能显示默认页面。
解决方案
方案1:适配新构建器的目录结构
修改Dockerfile中的COPY指令,指向环境子目录:
# 将原COPY指令 COPY --from=build /usr/local/app/dist/my-app-client /usr/share/nginx/html # 修改为 COPY --from=build /usr/local/app/dist/my-app-client/${ENVIRONMENT} /usr/share/nginx/html
如果固定使用production环境,也可以直接写死路径:
COPY --from=build /usr/local/app/dist/my-app-client/production /usr/share/nginx/html
方案2:临时保留旧browser构建器(不推荐长期使用)
在angular.json中调整项目的architect.build.builder配置为旧版构建器:
{ "projects": { "my-app-client": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", // 其他配置不变 } } } } }
这样产物结构与Angular 16时期一致,无需修改Dockerfile。
验证步骤
- 本地执行
npm run build -- --configuration=production,确认dist/my-app-client下存在对应环境的子目录 - 重新构建Docker镜像并运行容器
- 访问主机IP/端口,确认正常显示Angular应用
内容的提问来源于stack exchange,提问作者Wicked
相关产品推荐
相关产品推荐

