Skip to content

Instantly share code, notes, and snippets.

@remilapeyre
Created January 24, 2019 09:39
Show Gist options
  • Save remilapeyre/27673be52375a34b27bea831a93fc5e1 to your computer and use it in GitHub Desktop.
Save remilapeyre/27673be52375a34b27bea831a93fc5e1 to your computer and use it in GitHub Desktop.

Creating Images with Dockerfiles 2

Setting Default Commands

  1. 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.

  1. Rebuild your image:
$ docker image build -t myimage .
  1. 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.

  1. 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.

  1. Replace the CMD instruction in your Dockerfile with an ENTRYPOINT:
...
ENTRYPOINT ["ping"]
  1. 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?

  1. 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.

Combining Default Commands and Options

  1. Open your Dockerfile and modify the ENTRYPOINT instruction to include 2 arguments for the ping command:
...
ENTRYPOINT ["ping", "-c", "3"]
  1. If CMD and ENTRYPOINT are both specified in a Dockerfile, tokens listed in CMD are used as default parameters for the ENTRYPOINT command. Add a CMD with a default IP to ping:
...
CMD ["127.0.0.1"]
  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.

  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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment