Building Custom Container Images with Dockerfile
Introducing the Dockerfile
In this section, we will cover Dockerfiles in-depth, along with the best practices to use. So what is a Dockerfile?
A Dockerfile is simply a plain text file that contains a set of user-defined instructions. When the Dockerfile is called by the docker image build command, which we will look at next, it is used to assemble a container image. Dockerfile looks like the following:
FROM alpine:latest LABEL maintainer="adinusa <email@example.com>" LABEL description="This example Dockerfile installs NGINX." RUN apk add --update nginx && \ rm -rf /var/cache/apk/* && \ mkdir -p /tmp/nginx/ COPY files/nginx.conf /etc/nginx/nginx.conf COPY files/default.conf /etc/nginx/conf.d/default.conf ADD files/html.tar.gz /usr/share/nginx/ EXPOSE 80/tcp ENTRYPOINT ["nginx"] CMD ["-g", "daemon off;"]
As you can see, even with no explanation, it is quite easy to get an idea of what each step of the Dockerfile instructs the build command to do.
Before we move on to working our way through the previous file, we should quickly touch upon Alpine Linux.
Alpine Linux is a small, independently developed, non-commercial Linux distribution designed for security, efficiency, and ease of use. While small (see the following section), it offers a solid foundation for container images due to its extensive repository of packages, and also thanks to the unofficial port of grsecurity/PaX, which is patched into its kernel it offers proactive protection dozens of potential zero-day and other vulnerabilities.
Alpine Linux, due both to its size, and how powerful it is, has become the default image base for the official container images supplied by Docker. Because of this, we will be using it throughout this book. To give you an idea of just how small the official image for Alpine Linux is, let's compare it to some of the other distributions available at the time of writing:
As you can see from the Terminal output, Alpine Linux weighs in at only 4.41 MB, as opposed to the biggest image, which is Fedora, at 253 MB. A bare-metal installation of Alpine Linux comes in at around 130 MB, which is still almost half the size of the Fedora container image.