Dockerfile上的WORKDIR有什么意义? [英] What is the point of WORKDIR on Dockerfile?

查看:104
本文介绍了Dockerfile上的WORKDIR有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Docker.很多次,我已经看到 Dockerfile 具有 WORKDIR 命令:

I'm learning Docker. For many times I've seen that Dockerfile has WORKDIR command:

FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
EXPOSE 3000
CMD [ "npm", "start" ] 

我不能只省略 WORKDIR Copy ,而将 Dockerfile 放在项目的根目录吗?使用这种方法的缺点是什么?

Can't I just omit WORKDIR and Copy and just have my Dockerfile at the root of my project? What are the downsides of using this approach?

推荐答案

根据文档:

WORKDIR指令为任何RUN,CMD,紧随其后的ENTRYPOINT,COPY和ADD指令Dockerfile.如果WORKDIR不存在,即使以后的Dockerfile指令中未使用它,也将创建它.

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

此外,在 Docker最佳做法中它建议您使用它:

Also, in the Docker best practices it recommends you to use it:

...您应该使用WORKDIR而不是大量的说明,例如运行cd…&&做某事,这些事情很难阅读,排除故障并保持.

... you should use WORKDIR instead of proliferating instructions like RUN cd … && do-something, which are hard to read, troubleshoot, and maintain.

我建议保留它.

我认为您可以将Dockerfile重构为类似的内容:

I think you can refactor your Dockerfile to something like:

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ "npm", "start" ] 

这篇关于Dockerfile上的WORKDIR有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆