跳到主要内容

docker Dockerfile

Dockerfile

Instructions

  • .dockerignore
  • FROM Sets the Base Image for subsequent instructions.
  • MAINTAINER (deprecated - use LABEL instead) Set the Author field of the generated images.
  • RUN execute any commands in a new layer on top of the current image and commit the results.
  • CMD provide defaults for an executing container.
  • EXPOSE 指定容器运行时监听的网络端口,它并不会公开端口,仅起到声明的作用,公开的端口需要容器运行时使用-p参数。
  • ENV sets environment variable.
  • ADD copies new files, directories or remote file to container. Invalidates caches. Avoid ADD and use COPY instead.
  • COPY 将宿主机的文件复制到容器内。
  • ENTRYPOINT configures a container that will run as an executable.
  • VOLUME creates a mount point for externally mounted volumes or other containers.
  • USER sets the user name for following RUN / CMD / ENTRYPOINT commands.
  • WORKDIR 相当于cd命令,进入工作目录。
  • ARG defines a build-time variable.
  • ONBUILD adds a trigger instruction when the image is used as the base for another build.
  • STOPSIGNAL sets the system call signal that will be sent to the container to exit.
  • LABEL apply key/value metadata to your images, containers, or daemons.
  • SHELL override default shell is used by docker to run commands.
  • HEALTHCHECK tells docker how to test a container to check that it is still working.

多阶段构建

在基于.Net的应用程序时,需要一个SDK将源码编译为可执行程序,但是在生产中是不需要SDK的。 多阶段构建可以将生产时依赖与运行时依赖分开,减小整体image的文件大小。

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS build
COPY bin/Release/net7.0/publish/ app/

FROM nginx:alpine-slim AS final
WORKDIR /usr/share/nginx/html
COPY --from=build /app/wwwroot .
COPY /nginx.conf /etc/nginx/conf.d/default.conf

第一阶段:build

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS build COPY bin/Release/net7.0/publish/ app/

这个阶段基于 mcr.microsoft.com/dotnet/aspnet:7.0 镜像,将名字标记为 build。它主要用于将编译后的.NET应用程序从宿主机的 bin/Release/net7.0/publish/ 目录复制到镜像中的 app/ 目录。

第二阶段:final

第二阶段基于 nginx:alpine-slim 镜像,将名字标记为 final。这个阶段设置工作目录为 /usr/share/nginx/html,这是Nginx默认的静态文件服务目录。

  • COPY --from=build /app/wwwroot . 这一行使用了 --from=build 参数。这意味着它从第一阶段名为 build 的镜像中的 /app/wwwroot 目录复制文件到当前工作目录(即 /usr/share/nginx/html)。这样做的目的是将.NET应用程序的静态内容(如HTML、CSS、JavaScript文件等)复制到可以通过Nginx服务的目录中。
  • COPY /nginx.conf /etc/nginx/conf.d/default.conf 这一行则是将宿主机上的 nginx.conf 文件复制到容器中的 /etc/nginx/conf.d/default.conf,用于配置Nginx服务器。`**