Copying files during the build

Posted on Apr 04, 2019   ∣  1 min read  ∣  Docker

Copying files during the build

Monks copying books


Objectives

So far, we have installed things in our container images by downloading packages.

We can also copy files from the build context to the container that we are building.

Remember: the build context is the directory containing the Dockerfile.

In this chapter, we will learn a new Dockerfile keyword: COPY.


Build some C code

We want to build a container that compiles a basic “Hello world” program in C.

Here is the program, hello.c:

int main () {
  puts("Hello, world!");
  return 0;
}

Let’s create a new directory, and put this file in there.

Then we will write the Dockerfile.


The Dockerfile

On Debian and Ubuntu, the package build-essential will get us a compiler.

When installing it, don’t forget to specify the -y flag, otherwise the build will fail (since the build cannot be interactive).

Then we will use COPY to place the source file into the container.

FROM ubuntu
RUN apt-get update
RUN apt-get install -y build-essential
COPY hello.c /
RUN make hello
CMD /hello

Create this Dockerfile.


Testing our C program

Success!


COPY and the build cache


Details