在学习一个新概念之前,我们大多数人会思考以上三个问题。 **What, Why, How. **
那我们就顺着⬆️ 这个箭头思路往下看。 首先我们来了解一下 what
What (什么是 dockerfile)
** 在最开始接触dockerfile的时候,我的初步理解是dockerfile 类似linux shell 脚本主要的目的是为了将构建一个docker 镜像的过程通过dockerfile来记录并且描述。后来看了一下👇的官方描述,果不其然。**
Docker can build images automatically by reading the instructions from a
Dockerfile. ADockerfileis a text document that contains all the commands a user could call on the command line to assemble an image. Usingdocker buildusers can create an automated build that executes several command-line instructions in succession.
Why (为什么要使用 dockerfile)
A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.
Dockerfile 聚合了一切需要构建docker镜像的命令集,帮助快速构建docker镜像。
How (怎么样编写dockerfile)
在了解如何正确编写dockerfile, 我们先来了解一下dockerfile的相关常用语法
WORKDIR 字面意思是docker镜像的工作目录,
WORKDIR /app
该工作目录包含了镜像中所需要的一切依赖文件。
COPY 拷贝文件到工作目录
COPY package.json /app
ADD 添加文件到已存在的工作目录下方
COPY . /app
RUN 指令是为了执行一些命令,命令的输出决定了下一步的动作.
RUN npm install
RUN npm run build
EXPOSE 该指令主要是为了告知Docker,构建的镜像暴露某一个特定的网络端口并给到接下来该镜像运行的容器监听
EXPOSE 80/tcp
EXPOSE 80/udp
CMD 在Dockerfile中有且仅有一个CMD 命令, 如果你在dockerfile中写入多个CMD, 仅最后一个会生效
CMD ['npm', 'start']
CMD ['node', 'app.js']
# 最后一个CMD会覆盖之前的作为一个可执行的默认命令并暴露给执行的容器
最后附上我之前项目中的简单dockerfile 文件内容
FROM node:14-alpine
# create app directory
WORKDIR /app
# only copy the package.json file to work directory
COPY package*.json ./
# Install all packages
RUN npm install
# copy all other resources to work directory
ADD . /app
# build in work directory
RUN npm run build
EXPOSE 3001
# startCMD ["npm", "start"]
Happy coding 😄