【问题标题】:Adding built angular project to Docker based on nginx is very slow基于 nginx 向 Docker 添加构建的 Angular 项目非常慢
【发布时间】:2020-05-20 15:27:37
【问题描述】:

我有一个 Angular 项目。我用ng build --prod 构建它。然后我基于 nginx 容器构建了一个 docker 容器。只有我添加到这个 docker 容器的东西是 dist 文件夹及其内容和 nginx.conf。这是我的 Dockerfile:

FROM nginx

COPY dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf

在我的 dist 文件夹中没有太多内容。通常缩小的 js 目标文件和不超过 1MB 的其他资产(如图片)。 现在,如果我运行docker build .,那么有时最多需要 10 分钟才能出现任何日志,然后我得到“将构建内容发送到守护进程”等,最后成功。我注意到,如果我在 Angular 项目中更改某些内容并重新构建项目,则需要这 10 分钟。

所以流程是:

$ docker build .
(something happening here, it just does something without any logs for 10 minutes)
Sending build context to Docker daemon  627.5MB
Step 1/3 : FROM nginx
Step 2/3 : COPY dist /usr/share/nginx/html
 ---> e831f2851f75
Step 3/3 : COPY nginx.conf /etc/nginx/nginx.conf
 ---> f6264feec52b

所以我的问题是,是什么让 Docker 停了这么长时间,我怎样才能让它更快?

【问题讨论】:

  • 您可以在您的项目中添加一个.dockeringore 文件来忽略您的node_modules 目录,因为它通常很大并且可能需要很长时间才能将其发送到构建过程。
  • 我的 node_modules 不在构建上下文中。只有 dist 文件夹在并且 node_modules 不在 dist 文件夹中。或者它只是因为它与我的 Dockerfile 在同一个文件夹中而影响东西,即使我没有将它添加到 docker?
  • 构建上下文是docker build命令指定的目录。这是最后一个参数。 Docker 获取所有构建上下文,然后在其上应用构建命令(如COPY dist /usr/...)
  • 每天学习新东西。太感谢了。现在我的发布流程从 11 分钟缩短到了 1 分钟。

标签: angular docker nginx


【解决方案1】:

既然你在谈论你的 Angular 应用程序,它可能是检查的构建上下文。

通过将.dockerignore 文件添加到您的构建,确保忽略构建不需要的文件以提高性能。

Docker 构建上下文(在您的情况下为 .,即当前目录)被上传到 Docker 守护进程。

这意味着 PATH 中的所有文件都会被发送,而不仅仅是 Dockerfile 中列出的 ADD 文件。

见Docker Documentation

如果您排除 node_modules 文件夹和任何其他不必要的大目录/文件,您的构建可能会更快。


另外一些最佳实践

# add git-ignore syntax here of things you don't want copied into docker image

.git
*Dockerfile*
*docker-compose*
node_modules

Docker Captain Bret Fisher - Good dockerignore defaults

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2014-02-03
    • 2019-08-01
    • 1970-01-01
    • 2022-06-10
    • 2018-08-17
    相关资源
    最近更新 更多