What is a Dockerfile and how to use it

Dockerfile is the secret to building Docker images.

This is the workflow: first create a Dockefile, then build a Docker image from it with the following contentdocker build, And finally you ran a container from the image.

The Dockerfile is a text file that contains instructions on how to build the image.

These instructions are part of the configuration language and include things likeFROM,LABEL,RUN,COPY,ENTRYPOINT,CMD,EXPOSE,ENVAnd more.

Let's create the first Dockerfile:

Suppose you have a folder that contains a simple Node.js application, which consists ofapp.js, Apackage.jsonThis file lists several dependencies that you need to install before running the application, andpackage-lock.json.

Create a plain text file in it with the nameDockerfile, Without extension, with the following content:

FROM node:14
WORKDIR /usr/src/app
COPY package*.json app.js ./
RUN npm install
CMD ["node", "app.js"]

NOTE: use double quotes in the CMD line. Single quotes will result in an error.

In the first line we say which image we want to start from. This will be our base image. In this case it will take the official Node.js image, based on Alpine Linux, using Node 14. When creating a container from the Dockerfile, Docker will get that image from Docker Hub.

Next we set the working directory to /usr/src/app, which means all our commands will be run in that folder until we change it again. That’s a folder we know already exists in the Node image.

We copy the package.json, package-lock.json (using the * wildcard) and app.js files that are present in the current folder, into the working directory.

We run npm install to install the packages listed in the package.json file.

Then we expose port 3000 to the outside, since that’s what our app runs on. A container is 100% isolated from the network unless you expose one of its ports using the EXPOSE command. We’ll later see how we can map ports on our computer to ports in a Docker container.

Finally we run node app.js to start the app.

This is a Dockerfile, and we’ll soon see how to actually create a container from it.

More docker tutorials: