Understanding Dockerfile

We have used Docker images to create containers. We used images from Docker Hub to create those containers. But have you ever wondered how to create a Docker image? Docker can build images automatically by reading the instructions from a Dockerfile. DZone previously covered building Docker images with Jenkins.

Image title

Dockerfile

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Think of it as a shell script. It gathered multiple commands into a single document to fulfill a single task.

build command is used to create an image from the Dockerfile.

 $ docker build 

You can name your image as well.

 $ docker build -t my-image 

If your Dockerfile is placed in another path,

 $ docker build -f /path/to/a/Dockerfile . 

Let's first look at a Dockerfile and discuss those commands.

We are going to take the official MySQL Dockerfile as an example.

FROM debian:stretch-slim

# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added

RUN groupadd -r mysql && useradd -r -g mysql mysql

RUN apt-get update && apt-get install -y --no-install-recommends gnupg dirmngr && rm -rf /var/lib/apt/lists/*

RUN mkdir /docker-entrypoint-initdb.d

ENV MYSQL_MAJOR 8.0

ENV MYSQL_VERSION 8.0.15-1debian9

VOLUME /var/lib/mysql

# Config files

COPY config/ /etc/mysql/

COPY docker-entrypoint.sh /usr/local/bin/

RUN ln -s usr/local/bin/docker-entrypoint.sh /entrypoint.sh # backwards compat

ENTRYPOINT ["docker-entrypoint.sh"]

EXPOSE 3306 33060

CMD ["mysqld"]


Here's what's being done here:

These are the steps we will use to install MySql in our Linux machine. Now it's bundled inside the dockerfile to anyone to get and create images.

Read DZone’s DevOps’ tutorial on Docker, Kubernetes, and Azure.

Let's try to understand the purposes of these commands.

Dockerfile Commands

Review a list of all Docker commands. There are a few commands which are little confusing. Let's have a look at them.

COPY vs. ADD

Both commands serve a similar purpose, to copy files into the image.

Docker documentation recommends using the COPY command.

ENTRYPOINT vs. CMD

Related tutorial: How to perform Docker health checks.

VOLUME

You declare volume in your Dockerfile to denote where your container will write application data. When you run your container using -v   you can specify its mounting point.

Conclusion

Studying official Dockerfiles is a good way to learn more about the Dockerfile. We definitely have to start making our own Dockerfiles. 

 

 

 

 

Top