How to Conditionally Copy a File in Dockerfile
Been playing with Docker images a lot lately… like a lot:
One thing I want to do when building a Docker image from a Dockerfile: only copy over a file when it is there, otherwise, skip the file.
I want to be able to copy over certain files when building the Docker image if they exist in the current folder. Otherwise, the Docker image can take a different course of action, like generate a basic version of the optional file.
To follow along, please install Docker.
It also helps to have a Dockerfile to test it out. If you don’t have
one, the following
Dockerfile file contents will suffice:
All this does is start the ruby project and makes the working
/app. We will append the
COPY command will at the end of
Specify any optional files for the
COPY command with
* along with
one real file, the
COPY command needs to copy at least one file
over, even if there is more than one optional file to copy with the
To have the
COPY command in the Dockerfile copy over
which may or may not be there, write the command as:
This will ensure the
COPY operation is successful. The Dockerfile
It is vital to append
* to the optional files, otherwise,
will throw an error:
I stumbled upon this answer when perusing the Docker
didn’t look like anything special and I tried just
another_file* with no success.
What struck me was the answer had two arguments, one with the
without. With no other solutions in sight, I tried the command again,
but exactly as typed.
Specifying a file that exists with another that may exist is exactly
the behavior I want. I got it working by running:
I found the easiest way to always this is to always copy over the
Dockerfile, which must exist. So, if I want to copy a
Ruby projects or
package.json for node projects, I would specify in
the Dockerfile the command to be:
Then building the image would result in:
Dockerfile is not specifed, then
COPY throwns an error.
The Docker image build process stops.
Just by successfully copying over one file for Docker’s
command, the Docker image build process will continue, even if only
one of multiple files specified are successfully copied.