This blog will explain:
“docker build” Vs “docker run” Command
The “docker build” and “docker run” commands are both used to containerize the application in Docker containers. The key difference between these two commands is that the “docker build” command sends the build context and Dockerfile instructions to Docker Daemon to create the snapshot or image for a container. However, the “docker run” command is utilized to run the image or snapshot created by “docker build” to create the container and execute the program within the container.
How to Use “docker build” and “docker run” Commands?
To utilize the “docker build” and “docker run” commands to dockerize the program or application, go through the provided procedure.
Step 1: Create Program File
First, make a file named “index.html” file and paste the below provided HTML code into the file:
<head>
<style>
body{
background-color:rgb(9, 4, 4);
}
h1{
color:rgb(221, 219, 226);
font-style: italic;
}
</style>
</head>
<body>
<h1> This is First HTML page </h1>
</body>
</html>
Step 2: Make Dockerfile
Make a Dockerfile that contains instructions to containerize the “index.html” file. These instructions include the “FROM” statement to define a base image, the “COPY” statement to add a source file to the container, and the “ENTRYPOINT” or starting point for the container:
COPY index.html /usr/share/nginx/html/index.html
ENTRYPOINT ["nginx", "-g", "daemon off;"]
Step 3: Generate the Docker Image
After that, generate the snapshot of the container by reading the instructions of the Dockerfile using the “docker build -t <image> .” command. The “-t” option specifies the snapshot’s name:
Step 4: Create and Run the Container
After that, containerize the application by using the container snapshot or image in the “docker run” command. Here:
- “–name” option is utilized to define the container name.
- “-d” runs the container in detached mode.
- “-p” option assigns the local host exposed port for the container.
- “html:latest” is a snapshot of the container created through the “docker build” command:
For the confirmation, navigate the localhost port and check if the program is executing in a container or not:
We have explained the difference between “docker build” and “docker run” commands.
Conclusion
The key difference between “docker build” and “docker run” commands is that “docker build” is used to send the build context and Dockerfile instruction to Docker Daemon to create the snapshot of the container. However, the “docker run” command runs the snapshot created by “docker build” to create and execute the container. This write-up has explained the difference between the “docker build” and “docker run” commands and how to use them to containerize the application or program.