Building a container image

We use Docker to prepare our software and its execution environment by packing them onto a file system. We call this step building a container image. OK, let's do this. We will build our own version of an NGINX server on Ubuntu, my-nginx, as a Docker image. Please note that the terms container image and Docker image will be used interchangeably throughout this book.

We create a directory called my-nginx and change to it:

$ mkdir my-nginx
$ cd my-nginx

Then, we create a file named Dockerfile with the following content:

FROM ubuntu
RUN apt-get update && apt-get install -y nginx
EXPOSE 80
ENTRYPOINT ["nginx", "-g", "daemon off;"]

We will explain the contents of Dockerfile line by line:

  • First, it says that we want to use the image named ubuntu as our base image. This ubuntu image is stored on the Docker Hub, a central image registry server hosted by Docker Inc.
  • Second, it says that we want to install NGINX and related packages using the apt-get command. The trick here is that ubuntu is a plain Ubuntu image without any package information, so we need to run apt-get update before installing packages.
  • Third, we want this image to open port 80, inside the container, for our NGINX server.
  • Finally, when we start a container from this image, Docker will run the nginx -g daemon off; command inside the container for us.

We are now ready to build our first Docker image. Type the following command to start building an image. Please note that there is dot at the end of the command:

$ docker build -t my-nginx .

You will now see something similar to the following output with different hash numbers, so don't worry. Steps 2 to 4 will take a couple of minutes to finish, as it will download and install NGINX packages into the image filesystem. Just make sure that there are four steps and it ends with the message Successfully tagged my-nginx:latest:

Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM ubuntu
---> ccc7a11d65b1
Step 2/4 : RUN apt-get update && apt-get install -y nginx
---> Running in 1f95e93426d3
...
Step 3/4 : EXPOSE 8080
---> Running in 4f84a2dc1b28
---> 8b89cae986b0
Removing intermediate container 4f84a2dc1b28
Step 4/4 : ENTRYPOINT nginx -g daemon off;
---> Running in d0701d02a092
---> 0a393c45ed34
Removing intermediate container d0701d02a092
Successfully built 0a393c45ed34
Successfully tagged my-nginx:latest

We now have a Docker image called my-nginx:latest locally on our machine. We can check that the image is really there using the docker image ls command (or docker images for the old-style, top-level command):

$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
my-nginx latest 0a393c45ed34 18 minutes ago 216MB

Basically, this is the build concept of Docker. Next, we continue with shipping images.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset