Docker - Copy File from Different Working Directory to Another Is Not Working

I'm using:

Docker 18.09.1
Ubuntu 16.04

I want to copy a file from a specific folder from my docker image to another folder in my docker image using the Dockerfile.

My docker commands are:

sudo docker build -t mytest .
sudo docker run mytest

My Dockerfile is:

FROM ubuntu:16.04

RUN mkdir -p out/
COPY . out/            <---- this works
COPY /usr/bin/yes /opt <---- this doesn't work!!

CMD out/helloworld

I have a C++ application called helloworld on my out/ working folder. However, I want to copy a file called "yes" which is under /user/bin/ to my /opt folder.

I've tried the COPY command and also the CMD command but without success.

I tried to check if the file was there by running the command on my Ubuntu VM:

docker run mytest ls -l /opt
total 0

My COPY try:

COPY /usr/bin/yes /opt

My CMD try:

CMD ["cp /usr/bin/yes /opt"]

Error:

COPY failed: stat /var/lib/docker/tmp/docker-builder737799611/usr/bin/yes: no such file or directory

Both doesn't work. How can I copy a file to another folder (inside the same docker image)?

2

2 Answers

This is stated here that you cannot use absolute path to copy file from your host to your container. It is not supported: . So you have to prepare all your files in your current directory first.

4

The COPY command copies files from the build context (that's the . at the end of the docker build command in your example, aka the current directory) into the image. You cannot copy files from outside of the build context into the image.

For your purposes, it appears you want to copy between two different locations inside your image, not from the build context at all. For that, as long as you have the cp command present in almost every base image, you can run:

RUN cp /usr/bin/yes /opt/

Or in the json/exec syntax:

RUN [ "cp", "/usr/bin/yes", "/opt/" ]

Note that the exec syntax requires you to separate the command any every argument into a separate json array entry. The exec syntax also will not be running a shell, so you cannot do things like variable expansion and I/O redirection, which isn't being done in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest