1

I want to copy the file to a folder location that is outside the working directory. I used the following lines in my docker file, but the files are not there when I look in the container.

WORKDIR /app

RUN cd ../opt/venv/lib/python3.7/site-packages/xxx/
COPY ./resources/abc.py .

When look a that /opt/venv/lib/python3.7/site-packages/xxx/ location the abc.py is not there

What is the issue with my approach? Appreciate your inputs.

Malintha
  • 4,512
  • 9
  • 48
  • 82

2 Answers2

2

You can't COPY a file from outside the build context. So if you are trying to COPY /opt/venv/lib/python3.7/site-packages/xxx/resources/abc.py into your docker image, and that is not in your build context, it will fail. Full stop.

Here's some annotated code.

# change to the /app directory in the container
WORKDIR /app

# run the command cd in the container.  cd is a shell builtin, and after
# this command finishes you will still be inside the /app directory in
# your container.
RUN cd ../opt/venv/lib/python3.7/site-packages/xxx/

# Attempt to copy ./resources/abc.py from your host's build context
# (NOT /opt/venv/lib/python3.7/site-packages/xxx/) into the container.
COPY ./resources/abc.py .

The basic fix for this is to first copy abc.py into your build directory. Then you will be able to copy it into your docker container during your build like so:

WORKDIR /app
COPY abc.py .
# /app/abc.py now exists in your container

Note on cd

cd is a shell builtin that changes the working directory of the shell. When you execute it inside a script (or in this case a docker RUN) it only changes the working directory for that process, which ends when the script ends. After which your working directory will be the one you started in. So you cannot use it in the way you were intending. Much better explanation here.

Take this Dockerfile for example:

FROM alpine:latest
  
RUN cd /opt      # cd to /opt
RUN pwd          # check current directory, you're STILL in '/'

RUN cd /opt && \
    pwd          # works as expected because you're still in the same process that cd ran in.
                 # But once you exit this RUN command you will be back in '/'
                 # Use WORKDIR to set the working directory in a dockerfile

Here's the output of building that Dockerfile (removed noisy docker output):

$ docker build --no-cache .
Sending build context to Docker daemon  3.584kB
Step 1/4 : FROM alpine:latest
Step 2/4 : RUN cd /opt
Step 3/4 : RUN pwd
/
Step 4/4 : RUN cd /opt &&     pwd
/opt
kthompso
  • 1,823
  • 6
  • 15
0

From what I understand, you're trying to copy a file into a specific location (/opt/venv/lib/python3.7/site-packages/xxx/) in your Docker image that is outside the WORKDIR you defined in the Dockerfile for your image.

You can easily do this by specifying the absolute destination path in the COPY command:

WORKDIR /app

COPY ./resources/abc.py /opt/venv/lib/python3.7/site-packages/xxx/abc.py
Faheel
  • 2,435
  • 24
  • 33