DEV Community

Joonhyeok Ahn (Joon)
Joonhyeok Ahn (Joon)

Posted on • Updated on


Docker tutorial - understanding of Dockerfile


What is Dockerfile?

Dockerfile is a text file that contains a set of instructions. If run, we can build an image. Then we can run containers with a built image

Why do we need it?

We can use pre-built images like Postgres. Yet, we have to build images for our core services though. To containerize this, we have to make Dockerfile. Thanks to its simplicity, we can start building our images with a few commands.

Essential commands

The following commands are the basic ingredients to build an image.

FROM tells the base image to start the process. E.g) linux-alpine
RUN and CMD tell commands to run.
The difference is RUN will get executed while building an image. CMD will get executed by default when we launch the built image.
ADD copies the files from the source to the destination inside the container.
ENV sets the environment variables
ARG variables are only available while building an image.
EXPOSE tells the Docker container to listen to specific ports.
WORKDIR sets the working directory for commands like RUN

Baking an image

Now you understand the basic commands, let's look at the following one.

# syntax=docker/dockerfile:1
FROM node:18-alpine
COPY . .
RUN yarn install --production
CMD ["node", "src/index.js"]
Enter fullscreen mode Exit fullscreen mode

With the base image node, it will copy all from /app to /app. Next, it will run yarn install for dependencies. Once it finishes the installation. The process completes.

Tip: CMD and EXPOSE will get run when starting a container based on this image.

To build an image, run

docker build -t first-try.
Enter fullscreen mode Exit fullscreen mode

This will build an image. If you pass ., Docker will look for Dockerfile in the current directory. After building an image, it will tag the image you pass. In this case, I tag it as a "first-try".
Tip: tag is not required. It's more for a human-readable label.

Starting a container

Once we have the Docker image baked, we can run a container. Run,

docker run -d first-try
Enter fullscreen mode Exit fullscreen mode

Tip: -d is the option for detached mode. If you pass this option, Docker will run in the background.

To see your container's status, run docker ps.


Now, you should be able to build an image and run containers with your image. What if we need to run more complicated software? What if it has a database or cache? Docker provides a tool docker compose for running a multi-container codebase. We will look into it in the next article.

If you like this content, follow @bitethecode or my Github

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<