Build a simple Docker image
In this step, you will learn how to build a simple Docker image using a Dockerfile
. A Dockerfile
is a text document that contains all the commands a user could call on the command line to assemble an image. Docker can build images automatically by reading the instructions from a Dockerfile
.
First, navigate to the ~/project
directory, which is your working directory for this lab.
cd ~/project
Now, let's create a simple Dockerfile
. We will create a file named Dockerfile
in the ~/project
directory.
nano Dockerfile
Inside the nano
editor, paste the following content:
FROM ubuntu:latest
RUN apt-get update && apt-get install -y cowsay
CMD ["cowsay", "Hello, Docker!"]
Let's break down this Dockerfile
:
FROM ubuntu:latest
: This instruction specifies the base image for our new image. We are starting with the latest version of the Ubuntu operating system.
RUN apt-get update && apt-get install -y cowsay
: This instruction executes commands during the image build process. We are updating the package list and installing the cowsay
package, which is a simple program that displays text in a cow's speech bubble.
CMD ["cowsay", "Hello, Docker!"]
: This instruction provides the default command to execute when a container is started from this image. In this case, it will run the cowsay
command with the argument "Hello, Docker!".
Save the file by pressing Ctrl + X
, then Y
, and Enter
.
Now that we have our Dockerfile
, we can build the Docker image. Use the docker build
command. The -t
flag is used to tag the image with a name and optionally a tag in the name:tag
format. The .
at the end of the command tells Docker to look for the Dockerfile
in the current directory.
docker build -t my-cowsay-image:latest .
You will see output indicating that Docker is building the image layer by layer, executing the instructions in the Dockerfile
. This process might take a few moments as it downloads the base image and installs the cowsay
package.
Once the build is complete, you can verify that the image has been created by listing the available images using the docker images
command.
docker images
You should see my-cowsay-image
listed in the output.
Finally, let's run a container from the image we just built to see if it works as expected.
docker run my-cowsay-image:latest
You should see the output of the cowsay
command:
_______
< Hello, Docker! >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
This confirms that our Docker image was built correctly and the default command is executing as intended.