- Add the following line to your Docker le from the last problem, at the bottom:
...
CMD ["ping", "127.0.0.1", "-c", "5"]
This sets ping
as the default command to run in a container created from this
image, and also sets some parameters for that command.
- Rebuild your image:
$ docker image build -t myimage .
- Run a container from your new image with no command provided:
$ docker container run myimage
You should see the command provided by the CMD
parameter in the Docker le running.
- Try explicitly providing a command when running a container:
$ docker container run myimage echo "hello world"
Providing a command in docker container run
overrides the command defined by CMD.
- Replace the
CMD
instruction in your Dockerfile with anENTRYPOINT
:
...
ENTRYPOINT ["ping"]
- Build the image and use it to run a container with no process arguments:
$ docker image build -t myimage .
$ docker container run myimage
You’ll get an error. What went wrong?
- Try running with an argument after the image name:
$ docker container run myimage 127.0.0.1
You should see a successful ping output. Tokens provided after an image name are
sent as arguments to the command specified by ENTRYPOINT
.
- Open your Dockerfile and modify the
ENTRYPOINT
instruction to include 2 arguments for theping
command:
...
ENTRYPOINT ["ping", "-c", "3"]
- If
CMD
andENTRYPOINT
are both specified in a Dockerfile, tokens listed inCMD
are used as default parameters for theENTRYPOINT
command. Add aCMD
with a defaultIP
to ping:
...
CMD ["127.0.0.1"]
- Build the image and run a container with the defaults:
$ docker image build -t myimage .
$ docker container run myimage
You should see it pinging the default IP, 127.0.0.1.
- Run another container with a custom IP argument:
$ docker container run myimage 8.8.8.8
This time, you should see a ping to 8.8.8.8. Explain the di erence in behavior between these two last containers.
In this exercise, we encountered the Docker le commands CMD
and ENTRYPOINT
.
These are useful for de ning the default process to run as PID 1 inside the
container right in the Docker le, making our containers more like executables
and adding clarity to exactly what process was meant to run in a given image’s
containers.