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

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

问题描述

我正在学习 Docker.很多次我看到 DockerfileWORKDIR 命令:

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" ] 

我不能只省略 WORKDIRCopy 并且只将我的 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 指令在Docker 文件.如果 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天全站免登陆