3.0 KiB
Lesson 2: Introduction to Docker image builds
-
Clone this git repository.
-
Change directory into
lesson02
:$ cd lesson02
-
Why are containers useful? What are their advantages over a traditional server?
- containers are light
- containers are portable
- containers are isolated
- containers can be run "immutably"
- containers are built hierarchically
- developers can create applications without a full server-stack
-
What are some limitations of containers?
- interaction is more difficult for multiple containers than for multiple server process (although Kubernetes helps)
- some overhead so not quite as fast as "bare-metal" processes
- there are several decades worth of server administration best practices and tools but only a few years for containers
- not good for large tightly-integrated applications (e.g., Oracle database)
-
Question: what is the difference between an "image" and a "container"? (See also this Stackoverflow question).
-
Most Docker images are build on top of existing "base" images. These base containers are usually hosted in Docker Hub. For example, all Debian releases come as Docker images; see https://hub.docker.com/_/debian for a list of the base Debian Docker images.
-
Let's build a "Hello, world." Docker image. We will build it on a Debian buster base. First, pull the Docker image:
$ docker pull debian:buster-slim # We pull the "slim" image to save disk space
-
Here is an application that echos "Hello, world." and then exits (this file is also in the current directory).
#!/bin/sh echo "Hello, world." exit 0
-
Now we create a "Dockerfile" that tells the build process how to create the image. We use
debian:buster-slim
as the base and "add" the commandrun.sh
. The first argument ofADD
is the local copy of the file and the second argument is where we want the file to be in the image.# Dockerfile FROM debian:buster-slim LABEL maintainer="adamhl@stanford.edu" ADD run.sh /root/run.sh
-
We want to make sure that the script will run, so make it executable.
# Dockerfile FROM debian:buster-slim LABEL maintainer="adamhl@stanford.edu" ADD run.sh /root/run.sh RUN chmod a+x /root/run.sh
-
Docker containers must be told which command to run. We do this with the
CMD
directive# Dockerfile FROM debian:buster-slim LABEL maintainer="adamhl@stanford.edu" ADD run.sh /root/run.sh RUN chmod a+x /root/run.sh CMD /root/run.sh
-
We are now ready to build the image:
$ docker build . -t hello-world $ docker images | grep hello-world
-
Question: what is the purpose of
.
(dot) in the abovedocker build
command? -
Note that the tag is
latest
(the default). -
Let's run this image in a container:
$ docker run --rm hello-world
-
Did you see what you expected?