This is a field guide to Docker. Docker is a platform that allows users to create containers that hold specific environments.

Docker is built with a client-server architecture. The client is referred to as “docker”. It listens to user inputs and forwards them to the Docker server. The Docker server is referred to as “dockerd” (or the Docker daemon). It takes commands from the client and executes them. The client and server do not have to be on the same computer.

Useful terms:

  1. Engine: a client-server application made of a Docker Server and a Docker Client.
  2. Client: a command-line interface manager. Listens for commands and forwards them to the Docker server using the Docker API.
  3. Server: a daemon and execution manager. Receives requests from Docker client and executes them on Docker objects.
  4. Object: a collection of Docker data.
    1. Image: a read-only template containing instructions for creating a Docker container. Images can be built from a Dockerfile.
    2. Container: a runnable instance of an image, containing processes in a specific environment.
    3. Service: a read-only template defining how a Docker container should work in production. Similar to a container in production use.
    4. Swarm: a group of Docker containers or services that run as a cluster.
      1. Node: a Docker machine in a swarm.
      2. Manager: a node that can accept human commands and forward them to workers.
      3. Worker a node that can perform tasks in response to commands.
    5. Stack: a group of related services that share dependencies and can be scaled together.
  5. Registry: a remote catalog of Docker images, available for download. Examples include Docker Hub and Docker Cloud. By default, Docker is configured to access Docker Hub. Users can change the configured registry.
  6. Dockerfile: a file that defines of an image.
  7. Task: a job requested by a user that creates and runs in a Docker service or container.

Useful Docker Commands

  1. docker-machine start
    # Start Docker machine

    docker-machine start starts the Docker engine. It enables docker commands to be run on a host.

    docker-machine allows users to manage that machine’s Docker server. Once the user’s shell session is pointed towards a managed host, users can manage it with docker commands.

    Docker for Mac and Docker for Windows provide a similar service with an attractive user interface.

  2. docker-machine env
    # Display Docker machine commands

    docker-machine env displays a list of useful docker-machine commands.

    Users can copy from it the commands necessary to configure their shell session.

  3. eval $(docker-machine env)
    # Configure shell

    Users should run this command to configure their shell to communicate with the current docker machine.

  4. docker-machine kill
    # Force stop Docker machine

    docker-machine kill force stops the Docker engine.

  5. # Navigate to the appropriate directory for this container.
  6. # It should contain the three sample files below.
  7. docker build -t friendlyhello .
    # Build image

    The “build” command builds a Docker image. This one assigns the “friendlyhello” tag to the image for better tracking.

    This particular example builds the image in the current directory.

    This command has these options:

    • ‐‐add-host: Add a custom host-to-IP mapping (host:ip)
    • ‐‐build-arg: Set build-time variables
    • ‐‐cache-from: Images to consider as cache sources
    • ‐‐cgroup-parent: Optional parent cgroup for the container
    • ‐‐compress: Compress the build context using gzip
    • ‐‐cpu-period: Limit the CPU CFS (Completely Fair Scheduler) period
    • ‐‐cpu-quota: Limit the CPU CFS (Completely Fair Scheduler) quota
    • ‐‐cpu-shares, -c: CPU shares (relative weight)
    • ‐‐cpuset-cpus: CPUs in which to allow execution (0-3, 0,1)
    • ‐‐cpuset-mems: MEMs in which to allow execution (0-3, 0,1)
    • ‐‐disable-content-trust: Skip image verification (default true)
    • ‐‐file, -f: Name of the Dockerfile (Default is ‘PATH/Dockerfile’)
    • ‐‐force-rm: Always remove intermediate containers
    • ‐‐iidfile: Write the image ID to the file
    • ‐‐isolation: Container isolation technology
    • ‐‐label: Set metadata for an image
    • ‐‐memory, -m: Memory limit
    • ‐‐memory-swap: Swap limit equal to memory plus swap: ‘-1’ to enable unlimited swap
    • ‐‐network: Set the networking mode for the RUN instructions during build
    • ‐‐no-cache: Do not use cache when building the image
    • ‐‐pull: Always attempt to pull a newer version of the image
    • ‐‐quiet, -q: Suppress the build output and print image ID on success
    • ‐‐rm: Remove intermediate containers after a successful build (default true)
    • ‐‐security-opt: Security options
    • ‐‐shm-size: Size of /dev/shm
    • ‐‐squash: Squash newly built layers into a single new layer
    • ‐‐stream: Stream attaches to server to negotiate build context
    • ‐‐tag, -t: Name and optionally a tag in the ‘name:tag’ format
    • ‐‐target: Set the target build stage to build.
    • ‐‐ulimit: Ulimit options

  8. docker images
    # List built images

    This command lists currently built Docker images.

    It is equivalent to docker image ls.

  9. docker image ls -a
    # List built images

    This command lists currently built Docker images.

    It is equivalent to docker images.

  10. docker image rm friendlyhello
    # Removes an image

    This command removes a Docker image from this machine

    This command has these options:

    • ‐‐force, -f: Force removal of the image
    • ‐‐no-prune: Do not delete untagged parents

  11. docker image rm $(docker image ls -a -q)
    # Removes all images

    This command removes all Docker images from the selected machine.

    This command has these options:

    • ‐‐force, -f: Force removal of the image
    • ‐‐no-prune: Do not delete untagged parents

  12. docker build -t friendlyhello .
  13. docker run -p 4000:80 friendlyname
    # Docker run

    This command runs an image as a container with the port specified port mapping.

    For a complete list of options, see the documentation.

  14. docker run -d -p 4000:80 friendlyname
    #

    This command runs an image as a container in detached mode in the background.

  15. docker container ls
    # List running containers

    This command lists all running containers on the Docker machine.

    This command has these options:

    • ‐‐all , -a: Show all containers (default shows just running)
    • ‐‐filter, -f: Filter output based on conditions provided
    • ‐‐format: Pretty-print containers using a Go template
    • ‐‐last, -n: Show n last created containers (includes all states) (default -1)
    • ‐‐latest, -l: Show the latest created container (includes all states)
    • ‐‐no-trunc: Don’t truncate output
    • ‐‐quiet, -q: Only display numeric IDs
    • ‐‐size, -s: Display total file sizes

  16. docker container ls -a
    # List containers

    This command lists all containers (running and not) on the Docker machine.

  17. docker container stop <hash>
    # Stop container (gracefully)

    This command stops the specified container gracefully.

    The “<hash>” value can be found using the docker container ls command.

  18. docker container kill <hash>
    # Force a container (forcefully)

    This command stops the specified container forcefully.

    The “<hash>” value can be found using the docker container ls command.

  19. docker container rm <hash>
    # Remove a container

    This command removes a container from the docker machine.

    This command has these options:

    • ‐‐force, -f: Force the removal of a running container (uses SIGKILL)
    • ‐‐link, -l: Remove the specified link
    • ‐‐volumes, -v: Remove the volumes associated with the container

  20. docker container rm $(docker container ls -a -q)
    # Remove all containers

    This command removes all containers from the docker machine.

  21. docker login
    # Connect to Docker Cloud

    This command logs in to Docker Cloud for this bash session.

    Docker Cloud allows users to store and access Docker images remotely.

  22. docker tag image username/repository:tag
    # Tag image to a registry

    This command tags a Docker image with a descriptive name. Tagging is how remote Docker image registries give images versions.

  23. docker push username/repository:tag
    # Upload image to a registry

    This command pushes an image or repository to a remote registry.

  24. docker run username/repository:tag
    # Run image from registry

    This variation of the run command runs a Docker image from a remote registry’s repository.

Sample Files

These files support the Docker language guide above. They were taken from the Docker docs.

Sample Dockerfile

Copy this text and paste it into a file named “Dockerfile” in the project directory.

  1. # Use an official Python runtime as a parent image
  2. FROM python:2.7-slim
  3. # Set the working directory to /app
  4. WORKDIR /app
  5. # Copy the current directory contents into the container at /app
  6. ADD . /app
  7. # Install any needed packages specified in requirements.txt
  8. RUN pip install -r requirements.txt
    # Run pip

    This command installs the dependent Python package listed in the requirements file using the pip package manager.

  9. # Make port 80 available to the world outside this container
  10. EXPOSE 80
  11. # Define environment variable
  12. ENV NAME World
  13. # Run app.py when the container launches
  14. CMD ["python", "app.py"]

requirements.txt

Copy this text and paste it into a file named “requirements.txt” in the same directory as the dockerfile.

  1. Flask
  2. Redis

app.py

Copy this text and paste it into a file named “app.py” in the same directory as the dockerfile.

  1. from flask import Flask
  2. from redis import Redis, RedisError
  3. import os
  4. import socket
  5. # Connect to Redis
  6. redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)
  7. app = Flask(__name__)
  8. @app.route("/")
  9. def hello():
  10.     try:
  11.         visits = redis.incr("counter")
  12.     except RedisError:
  13.         visits = "<i>cannot connect to Redis, counter disabled</i>"
  14.     
  15.     html = "<h3>Hello {name}!</h3>" \
  16.         "<b>Hostname:</b> {hostname}<br/>" \
  17.         "<b>Visits:</b> {visits}" # Access hostname

    Accessing a hostname when inside a container retrieves the container ID, which acts similar to a process ID for a running executable.

  18.     return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)
  19. if __name__ == "__main__":
  20.     app.run(host='0.0.0.0', port=80)