/

Dockerfiles: A Guide to Building Docker Images

Dockerfiles: A Guide to Building Docker Images

In the world of Docker, a Dockerfile serves as the recipe for building a Docker image. It outlines the necessary steps and instructions to construct an image that can then be used to run a container.

The workflow for using a Dockerfile is as follows: first, you create the Dockerfile, then you build the Docker image using the docker build command, and finally, you run a container from the created image.

A Dockerfile is essentially just a plain text file that includes a set of instructions for building an image. These instructions are written in a configuration language and utilize keywords such as FROM, LABEL, RUN, COPY, ENTRYPOINT, CMD, EXPOSE, ENV, and more.

To create your first Dockerfile, let’s imagine you have a folder containing a simple Node.js app. Within this folder, you have an app.js file, a package.json file that lists the dependencies required by the app, and a package-lock.json file.

To begin, create a text file named Dockerfile (without any file extension) and populate it with the following content:

1
2
3
4
5
6
FROM node:14
WORKDIR /usr/src/app
COPY package*.json app.js ./
RUN npm install
EXPOSE 3000
CMD ["node", "app.js"]

NOTE: Please make sure to use double quotes in the CMD line. Using single quotes will result in an error.

In the first line of the Dockerfile, we specify the base image that we want to start from. This image acts as the foundation for our custom image. In this case, we use the official Node.js image from Docker Hub, which is based on Alpine Linux and specifically uses Node 14.

Next, we set the working directory to /usr/src/app, which becomes the default location for all subsequent commands within the Dockerfile. This directory already exists in the Node.js image, so we can confidently use it as our workspace.

Following that, we copy the package.json, package-lock.json, and app.js files from the current directory (using the * wildcard) into the working directory of the Docker image.

Then, we use the RUN command to execute npm install within the image, which installs all the dependencies listed in the package.json file.

After that, we employ the EXPOSE command to expose port 3000 to the outside world. By default, containers are completely isolated from the network, unless specific ports are exposed.

Finally, we run the command node app.js to start our Node.js app within the container.

And there you have it! This is a Dockerfile, serving as the blueprint for creating a container. Soon, we’ll explore how to effectively utilize this Dockerfile to construct a container that perfectly suits our needs.

tags: [“Dockerfile”, “Docker image”, “Docker container”, “Docker Hub”, “configuration language”, “FROM“, “LABEL“, “RUN“, “COPY“, “ENTRYPOINT“, “CMD“, “EXPOSE“, “ENV“]