Making your first container

Making a container is something easily done with the Docker software and the docker build command. This command uses a manifest that details how to create the container, called a Dockerfile.

Let's start with the simplest possible container. Create a file called a Dockerfile and add this to it:

FROM alpine
CMD ["/bin/sh", "-c", "echo 'hello world'"]

And then, invoke build:

docker build .

If you see a response like this:

"docker build" requires exactly 1 argument.
See 'docker build --help'.
Usage: docker build [OPTIONS] PATH | URL | -
Build an image from a Dockerfile

Then you are either missing the . in the command, or ran the command in a directory different from where you created the Dockerfile. The . is telling docker where to find Dockerfile (. meaning] in this current directory).

What you should see is some output akin to the following:

Sending build context to Docker daemon  2.048kB
Step 1/2 : FROM alpine
latest: Pulling from library/alpine
88286f41530e: Pull complete
Digest: sha256:f006ecbb824d87947d0b51ab8488634bf69fe4094959d935c0c103f4820a417d
Status: Downloaded newer image for alpine:latest
---> 76da55c8019d
Step 2/2 : CMD /bin/sh -c echo 'hello world'
---> Running in 89c04e8c5d87
---> f5d273aa2dcb
Removing intermediate container 89c04e8c5d87
Successfully built f5d273aa2dcb

This image only has an ID, f5d273aa2dcb, not a name, but this is sufficient for us to see how this works. If you run this sample example locally, you will get a different ID that uniquely identifies the container image. You can run the code in the container image using the docker run f5d273aa2dcb command. This should result in you seeing the following output:

hello world

Take a moment to run docker history f5d273aa2dcb and docker inspect f5d273aa2dcb on the image you just created.

When you're done, we can delete the Docker image we just made with the following command:

docker rmi f5d273aa2dcb

If you get an error removing an image, which can happen if you have a stopped container that references the image locally, you can force the removal with the addition of -f. For example, the command that will force the removal of a local image would be:

docker rmi -f f5d237aa2dcb