An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Docker tutorial - understanding of Dockerfile
Content
- What is Dockerfile?
- Why do we need it?
- Essential commands
- Baking an image
- Starting a container
- Conclusion
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-alpineRUN
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 variablesARG
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:1FROM node:18-alpineWORKDIR /appCOPY . .RUN yarn install --productionCMD ["node", "src/index.js"]EXPOSE 3000
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.
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
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
.
Conclusion
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
Original Link: https://dev.to/bitethecode/docker-tutorial-understanding-of-dockerfile-2mjb
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To