Hands-On Docker for Microservices with Python
上QQ阅读APP看书,第一时间看更新

Building your service with a Dockerfile

It all starts with a container. As we said in Chapter 1, Making the Move – Design, Plan, and Execute, containers are a packetized bundle of software, encapsulated in a standard way. They are units of software that can be run independently, as they are totally self-contained. To make a container, we need to build it.

Remember our description of a container as a process surrounded by its own filesystem. Building a container constructs this filesystem.

To build a container with Docker, we need a definition of its content. The filesystem is created by applying layer after layer. Each Dockerfile, the recipe for generating a container, contains a definition of steps to generate a container.

For example, let's create a very simple Dockerfile. Create a file called example.txt with some example text and another called Dockerfile.simple with the following:

# scratch is a special container that is totally empty
FROM scratch
COPY example.txt /example.txt

Now build it using the following command:

$ # docker build -f <dockerfile> --tag <tag> <context>
$ docker build -f Dockerfile.simple --tag simple .
Sending build context to Docker daemon 3.072kB
Step 1/2 : FROM scratch
--->
Step 2/2 : COPY example.txt /example.txt
---> Using cache
---> f961aef9f15c
Successfully built f961aef9f15c
Successfully tagged simple:latest

$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
simple latest f961aef9f15c 4 minutes ago 11B

This creates a Docker image that only contains the example.txt file. It's not very useful, but quite small—only 11 bytes. That's because it inherits from the empty container, scratch. It then copies the example.txt file inside the location in the /example.txt container.

Let's take a look at the docker build command. The Dockerfile is defined with the -f parameter, the tag of the resulting image is defined with --tag , and the context parameter is defined as dot (.). The context parameter is the reference to where to look for the files defined in the steps in the Dockerfile.

The image also has the image ID f961aef9f15c, which is assigned automatically. This is a hash of the contents of the filesystem. We'll see later why this is relevant.