Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (2.3k points)

I want to use these with docker:

git clone XYZ
cd XYZ
make XYZ

But I can't as the cd command is not there. I do not wish to make xyz as the full path everytime, are there any workarounds?

2 Answers

0 votes
by (6.9k points)

Easy ! Just use the WORKDIR command to change the directory you want to. Any other commands you use beyond this command will be executed in the directory you have set. 

Here's an example:

RUN git clone XYZ 
WORKDIR "/XYZ"
RUN make

It is also a better practice to make use of WORKDIR in docker.

OR

You can do this by using a much more complex RUN command, like given below:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

And this way it only gets to the last command [ pip install ] only if the previous commands were successfully executed.

Combining the different RUN commands is recommended. This is because every time RUN command is executed an AUFS layer and a new commit are created and there is a limit for them, so be careful about them.

Hope that helped :)


If you are looking for help from professional DevOps engineers who work with docker, try out docker training course.

0 votes
by (1.7k points)

In a Dockerfile, for each command, 'RUN' executes in a new shell; thus, 'cd' alone will not keep the change to the working directory for other commands. There are, however, two workarounds for this limitation:

Use the WORKDIR Command

The WORKDIR command lets you change the working directory for further commands in the Dockerfile. You can use it in the following format:

WORKDIR /path/to/your/directory # Change to your directory

RUN git clone XYZ # Clone the repository

WORKDIR XYZ # Change to cloned directory

RUN make # Run make

Run Several Commands in One 'RUN' Command

If you dislike changing the working directory too many times, you can run all your commands in one 'RUN' command:

RUN git clone XYZ && \

cd XYZ && \

make

For such a case, 'cd' is relevant only within the chain of commands because it's chained with both 'git clone' and 'make,' thus succeeding in its task.

Set Full Paths using Environment Variables

If you really abhor entering full paths you could define an environment variable to hold the path of the cloned directory:

ENV REPO_DIR /path/to/your/directory/XYZ

RUN git clone XYZ $REPO_DIR && \

   cd $REPO_DIR && \

   Make

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...