Creating Images with Dockerfiles (2/2)
By the end of this exercise, you should be able to:
- Define a default process for an image to containerize by using the
ENTRYPOINTorCMDDockerfile commands - Understand the differences and interactions between
ENTRYPOINTandCMD
Setting Default Commands
Add the following line to your Dockerfile from the last problem, at the bottom:
... CMD ["ping", "127.0.0.1", "-c", "5"]This sets
pingas the default command to run in a container created from this image, and also sets some parameters for that command.Rebuild your image:
[centos@node-0 myimage]$ docker image build -t myimage .Run a container from your new image with no command provided:
[centos@node-0 myimage]$ docker container run myimageYou should see the command provided by the
CMDparameter in the Dockerfile running.Try explicitly providing a command when running a container:
[centos@node-0 myimage]$ docker container run myimage echo "hello world"Providing a command in
docker container runoverrides the command defined byCMD.Replace the
CMDinstruction in your Dockerfile with anENTRYPOINT:... ENTRYPOINT ["ping"]Build the image and use it to run a container with no process arguments:
[centos@node-0 myimage]$ docker image build -t myimage . [centos@node-0 myimage]$ docker container run myimageYou'll get an error. What went wrong?
Try running with an argument after the image name:
[centos@node-0 myimage]$ docker container run myimage 127.0.0.1You should see a successful ping output. Tokens provided after an image name are sent as arguments to the command specified by
ENTRYPOINT.
Combining Default Commands and Options
Open your Dockerfile and modify the
ENTRYPOINTinstruction to include 2 arguments for the ping command:... ENTRYPOINT ["ping", "-c", "3"]If
CMDandENTRYPOINTare both specified in a Dockerfile, tokens listed inCMDare used as default parameters for theENTRYPOINTcommand. Add aCMDwith a default IP to ping:... CMD ["127.0.0.1"]Build the image and run a container with the defaults:
[centos@node-0 myimage]$ docker image build -t myimage . [centos@node-0 myimage]$ docker container run myimageYou should see it pinging the default IP,
127.0.0.1.Run another container with a custom IP argument:
[centos@node-0 myimage]$ docker container run myimage 8.8.8.8This time, you should see a ping to
8.8.8.8. Explain the difference in behavior between these two last containers.
Conclusion
In this exercise, we encountered the Dockerfile commands CMD and ENTRYPOINT. These are useful for defining the default process to run as PID 1 inside the container right in the Dockerfile, making our containers more like executables and adding clarity to exactly what process was meant to run in a given image's containers.