Docker如何在Dockerfile中保存和恢复WORKDIR?

问题描述 投票:0回答:3

我有一个来自图像的Dockerfile。我想修改它并添加一些文件操作,这些操作将相对于不同的WORKDIR而不是FROM图像给出的操作。因此,我想在修改WORKDIR之前将WORKDIR保存到变量,并在命令结束后从该变量恢复WORKDIR。怎么做?

通缉结果:

Dockerfile伪代码:

FROM centos:7
some original commands
some original commands
...
var=WORKDIR #save WORKDIR <== how to do that?

WORDIR /my/path/
my commands
my commands

...
WORKDIR = var # restore path that was before <== how to do that?
docker save dockerfile restore working-directory
3个回答
0
投票

添加到WSMathias9的答案:

除非WORKDIR被你正在使用的基本图像改变,否则默认情况下总是/,你可以在完成时将其设置为/,因为它是centos图像的默认值

但是,如果你使用WORKDIR作为cd的替代品,只需在cd中使用RUN

而不是例如:

FROM centos:7

WORKDIR /folder
RUN mycommand

做:

FROM centos:7

RUN cd /folder && mycommand

0
投票

如果您试图从基本图像中保留WORKDIR,则无法进行

如果在同一个dockerfile中设置它,WORKDIR将只有值。

如果您尝试使用不同的工作目录来执行不同的命令:

Dockerfile伪代码:

FROM centos:7
some original commands
some original commands
...
ARG PATH1=/path1
ARG PATH2=/path1

my commands
my commands

WORKDIR PATH1
my commands
my commands

WORKDIR PATH2
my commands
my commands

WORKDIR PATH1
my commands
my commands

...
WORKDIR PATH1 # restore path that was before <== how to do that?

0
投票

您可以创建环境变量。

ENV WORKDIR=/my/path/
WORDIR $WORKDIR
© www.soinside.com 2019 - 2024. All rights reserved.