A Dockerfile is the recipe to build a Docker image.

This is the workflow: first you create a Dockefile, then you built a Docker image from it using docker build, and finally you run a container from the image.

A Dockerfile is a text file with instructions on how to build an image.

Those instructions are part of a configuration language, which includes keywords like FROM, LABEL, RUN, COPY, ENTRYPOINT, CMD, EXPOSE, ENV and more.

Let’s create our first Dockerfile:

Let’s say you have a folder with a simple Node.js app composed by an app.js, a package.json file that lists a couple dependencies you need to install before running the app, and package-lock.json.

Inside it, create a plain text file named Dockerfile, with no extension, with this content:

FROM node:14
WORKDIR /usr/src/app
COPY package*.json app.js ./
RUN npm install
EXPOSE 3000
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.