Docker Cheat Sheet - 1515532697
Docker Cheat Sheet - 1515532697
Docker
Contents
Docker Engine Installation 1
Pull an Image from a Registry (Using Docker Pull and Docker Images) 2
Use CLI Commands to Manage Images (List, Delete, Prune, RMI, etc) 4
Inspect Images and Report Specific Attributes Using Filter and Format 6
Deploy, Configure, Log In to, Push, Pull, and Delete an Image in a Registry 17
Complete Setup of a Swarm Mode Cluster with Managers and Worker Nodes 20
Extend the Instructions to Run Individual Containers into Running Services Under Swarm
and Manipulate a Running Stack of Services 22
Convert an Application Deployment into a Stack File Using a YAML Compose File with ‘docker
stack deploy’ 28
Create a Docker Bridge Network for a Developer to Use for their Containers 29
Publish a Port So That an Application is Accessible Externally and Identify the Port and IP It
Is On 30
Set Up and Configure Universal Controller Plane and Docker Trusted Registry for Secure
Cluster Management 34
• sudo systemctl enable docker && systemctl start docker && systemctl
status docker
• Will need to log out and back in, then check with ‘docker images’
• https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/#upgrade-docker-
after-using-the-convenience-script
-1-
Title J. Titleski Linux Academy + Cloud Assessments
• If you need a specific version, you can do sudo apt-get install docker-
ce=[VERSION]
• sudo systemctl enable docker && systemctl start docker && systemctl
status docker
• Will need to log out and back in, then check with ‘docker images’
• /usr/lib/systemd/system/docker.service
• docker images
• --filter (-f) [name=value] - display the image indicated within the filter
• label
• dangling
• before
• since
• reference
• `docker rm \docker ps -a -q\\` (removes all previously run but stopped containers)
-3-
Title J. Titleski Linux Academy + Cloud Assessments
• docker search
Tag an Image
• docker tag
• SOURCE[:TAG] TARGET[:TAG]
• tag by reference ID
• tag by name
• build
-4-
Title J. Titleski Linux Academy + Cloud Assessments
• history
• import
• inspect
• options - https://docs.docker.com/engine/reference/commandline/inspect/#options
• alone, provides JSON formatted output of every aspect of the indicated image
• load
• standard input
• ls
• prune
• pull
• push
• rm
• save
• tag
• [imagename]
• -i - interactive - STDIN
• -t - terminal/pseudo TTY
• -d - detached
-6-
Title J. Titleski Linux Academy + Cloud Assessments
• --publish (-p) [#[:#]] - publish container port to indicated host port - local:container
• --env (-e) [name=value] - assigns variables and their values, can set
multiple --env on command line
• --mount type=[volume/bind,src=[path],dst=[path] OR
target=[containerpath]]
• docker exec
• -i - interactive - STDIN
• -t - terminal/pseudo TTY
• -d - detached
• docker build
• -f (--file) [PATH/DockerfileName]
-7-
Title J. Titleski Linux Academy + Cloud Assessments
• builds the indicated Dockerfile with the indicated tag in the current build context
• --build-arg [var=value]
• --add-host=[hostname:IP]
• build contexts
• git repository
• tarball
• text (Dockerfile)
• FROM
• ARG SOME_VARIABLE=value
• NOTE: ARG is the only instruction that can precede FROM in Dockerfile
• FROM base:${SOME_VARIABLE}
• RUN
• [“command”, “parm1”, “parm2”] - exec form - does not require a shell executable,
avoid shell string munging, parsed as JSON array
• commands can be run over multiple lines by appending a backslash (`\`) to the end of
the line and continuing on the next
• CMD
• ONLY ONE CMD per Dockerfile (if more than one in the file, only last one will run)
-9-
Title J. Titleski Linux Academy + Cloud Assessments
• provides the defaults for container execution (generally an executable, but if not
an executable, provide an ENTRYPOINT)
• NOTE: RUN executes command(s) in a new layer and creates a new image. E.g.,
it is often used for installing software packages. CMD sets default command and/
or parameters, which can be overwritten from command line when the Docker
container runs.
• LABEL
• key/value pair
• when adding multiple labels in a Dockerfile, combine into one longer line with one
LABEL, otherwise, each LABEL produces a new layer for the image
• MAINTAINER (Deprecated)
• <name>
• EXPOSE
• `<port> [<port>/<protocol>…]`
• protocol can be UDP or TCP associated with the indicated port, default is TCP with
no specification
• NOTE: does not publish the port, simply makes it available to be published and
documents requirements of your image
• ENV
- 10 -
Title J. Titleski Linux Academy + Cloud Assessments
• when adding multiple environment variables in a file, putting them all on one longer
line will produce a single layer whereas multiple ENV statements produce a layer for
each
• NOTE: ENV variables persist and can be used in containers instantiated on the built
image
• ADD
• copies files, directories, or URLs as indicated into the image filesystem in the path
provided
• `<src>… <dest>`
• if using protected URLs that require auth, use RUN wget or curl as ADD does not
support auth
• NOTE: any other type of file will be copied, with metadata, to the indicated
destination
• NOTE: be sure the destination, when a directory, has a trailing slash (//) OR it will
be treated as a destination file and be written as such
• COPY
• copies files or directories as indicated into the image filesystem in the path provided
- 11 -
Title J. Titleski Linux Academy + Cloud Assessments
• `<src>… <dest>`
• --from=<name|index>
• allows you to specify a file or directory (source) from a previous build stage
• contents of directories are copied to the destination path, NOT the directory itself
• NOTE: any other type of file will be copied, with metadata, to the indicated
destination
• NOTE: be sure the destination, when a directory, has a trailing slash (//) OR it will
be treated as a destination file and be written as such
• ENTRYPOINT
• creates a container that, when instantiated, effectively runs as an executable with the
item in the ENTRYPOINT
• NOTE: when used with CMD to provide parms, CMD must be AFTER the ENTRYPOINT
• can be overriden at run time with --entrypoint as part of the docker run
command
• exec form parsed as JSON array, does not invoke a shell in exec form
• NOTE: to ignore parms in CMD and to be sure docker stop cleanly stops the container,
begin your ENTRYPOINT with exec
• VOLUME
• [“/path”]
• creates a mount point with the indicated name and indicates it is an external mount
point when instantiated from the image by a container
- 12 -
Title J. Titleski Linux Academy + Cloud Assessments
• host directories are declared at run time and NOT within the Dockerfile
• USER
• <user>[:<group>] or <UID>[:<GID>]
• set username (UID) and (optionally) the GID to use when running the image and to be
used with RUN, CMD, or ENTRYPOINT instructions in the Dockerfile
• WORKDIR
• /path/dir
• set the working directory for any RUN, CMD, COPY, ADD, or ENTRYPOINT instruction in
the Dockerfile
• ARG
• <name>[<default value>]
• defines arguments that can be passed in by user at build time using docker build
• i.e., a user to run command as, a working directory, file name to use, changeable
parms, etc.
• predefined ARGs
• HTTP_PROXY
• HTTPS_PROXY
• FTP_PROXY
• NO_PROXY
• can cause additional layers to be built when the ARG is different on subsequent builds
• STOPSIGNAL
- 13 -
Title J. Titleski Linux Academy + Cloud Assessments
• the specific signal (by name) to send to containers when docker stop <name> is
issued
• SHELL
• [“executable”, “parms”]
• overrides the /bin/sh -c behavior for shell-based instructions in RUN, CMD, etc.
• --no-trunc
• import the container (to flatten the image, losing the history in the process)
- 14 -
Title J. Titleski Linux Academy + Cloud Assessments
• UNOFFICIAL: docker-squash
• https://github.com/jwilder/docker-squash
• using a ‘pluggable’ architecture, Docker supports multiple storage drivers that control how
images and containers are stored and managed on your Docker host
• Docker CE
• docker info
• | grep “Storage Driver” - will show you the storage driver in the active configuration
• /etc/docker
• { “storage-driver”: “devicemapper” }
- 15 -
Title J. Titleski Linux Academy + Cloud Assessments
• NOTE: once a new storage driver is enabled, it will make any images previously downloaded
using the previous driver unavailable (and changing back or deleting the daemon.json
file will cause docker.service to fail)
• NOTE: for our demo, because of port restrictions, we will add local host /etc/hosts entries
on several Docker hosts - the first being the host of the registry so that ‘myregistrydomain.
com’ points to the private IP and the second on another Docker host that points /etc/hosts
‘myregistrydomain.com’ to the private IP of the system hosting the registry
• copy the certificate needed for this registry to the new directory
• cp /home/user/certs/dockerrepo.crt /etc/docker/certs.d/
myregistrydomain.co m:5000/ca.crt
• run the container needed to create the authentication information for the registry, passing
in a user
> auth/htpasswd
• confirm that the certificate and key exist in the `~/certs` directory
• confirm that the htpasswd authentication file exists in the `~/users` directory
• run the container that allows the private registry to work on default port 5000 with the
appropriate TLS and basic user authentication requirements
• local test
• now succeeds
• note that this only affects the repository on the host NOT the registry we set up
• should pull the image and be visible locally with ‘docker images’
• copy remote ca.crt to this directory (note that each host using the repository must
have this file in the right directory)
• test
• FAILS, no authentication
• GET /v2/<name>/tags/list
• for manifests (to get the digest needed to work with images and layers)
- 18 -
Title J. Titleski Linux Academy + Cloud Assessments
• DELETE /v2/<name>/manifests/<reference>
• supported types
• none
• json-file
• syslog
• journald
• gelf
• fluentd
- 19 -
Title J. Titleski Linux Academy + Cloud Assessments
• awslogs
• splunk
• the docker logs command ONLY works when coonfigured for json-file and journald
• docker swarm
• take note (copy) the necessary docker swarm join command and token
• join-token worker
• will redisplay the command and token needed for a node to join a swarm
• docker swarm
• verify
• on management node
• docker node ls
- 20 -
Title J. Titleski Linux Academy + Cloud Assessments
• Although containers now give us the flexibility, portability, granularity, and abstraction that
allow us to get the most out of our environments and deployments, it quickly became ‘too
limited’.
• We needed an easier way to deploy complex configurations in highly available and easily
scalable implementations. This required the development of cluster management and
control software (like Docker Swarm or Kubernetes) to work directly with Docker containers.
As a result, a new paradigm was needed to address the requirements of highly scalable,
clustered container environments.
• Whereas containers are limited to the single host they are started on, services are
containers that live on a scalable number of ‘workers’ in a cluster of systems. Docker
Swarm then handles access to and availability of that service across those worker nodes,
eliminating the challenges of routing and accessing individual containers.
• Scalability is key in the enterprise, both up and down, to maximize your infrastructure
spend, and services allow you granular control of CPU, Memory, Disk, Network, and more.
• access to the nodes gives access to the TLS key used to encrypt them
• locking a cluster further protects those keys in environments once the restarts until the
unlock key is provided
- 21 -
Title J. Titleski Linux Academy + Cloud Assessments
• will allow nodes to join, otherwise function normally UNTIL management node restarts,
then nothing will run until the swarm is unlocked
• additional managers can join, but, would need to be unlocked with same key on restart
• will update existing swarm so it is locked, will display the unlock key
• keep old key logged somewhere for a period of time until you can verify all
management nodes have the update
• docker service ls
• --publish [#:#] - publish indicated ports and map to underlying host - NOTE:
bypasses routing mesh
• --network [network name] - can be used to bypass the mesh network for an overlay
• --replicas [#]
- 23 -
Title J. Titleski Linux Academy + Cloud Assessments
• --secret [filename] - allows the service access to Docker secrets, use this for
each secret
• Docker (using the routing mesh) will make a service available on each node (even if a
replica is not running on it) on the target port
• additional options
• type=[type of mount]
• tmpfs
• -- placement-pref
• `‘spread=node.labels.datacenter=[value]’`
• reservation allows the specification of a ‘soft’ limit, must be set lower than the
‘hard’ limit (in limit-cpu setting), used when contention is found, the limit-cpu is the
MAX CPU that the container can use
• this is a RATIO number of the number of CPUs available (i.e. limit of 1.5 on a 2
CPU system gives one and a half max to container)
- 24 -
Title J. Titleski Linux Academy + Cloud Assessments
• a service that is replicated one or more times to a given number of instances and
nodes
• global service
• --mode [global]
- 25 -
Title J. Titleski Linux Academy + Cloud Assessments
• Restore
• --hostname
• --mount
• --env
• .Service.ID
• .Service.Name
- 26 -
Title J. Titleski Linux Academy + Cloud Assessments
• .Service.Labels
• .Node.ID
• .Task.ID
• .Task.Name
• .Task.Slot
• examples
• could be used to create dynamic mount points to share with the containers
• hostnames could be pulled and autoadded to DNS if desired (of container instances in
the service)
• docker service ls
• provides a ‘human readable’ method of showing the JSON output from inspect
commands
• NOTE: you can add multiple consecutive labels in the same line
- 27 -
Title J. Titleski Linux Academy + Cloud Assessments
• example
• in the example below, we are creating an HTTPD service running in a two node cluster
and running two replicas (which would normally run one on each host), we will set the
service however, to run only on the node with the indicated label
• node.id
• node.hostname
• node.role
• node.labels
• engine.labels
• epel-release
• python-pip
• create Dockerfile
• docker-compose up -d
• docker-compose ps
• docker-compose push
• NOTE: adding a container to a network does NOT disconnect from previous, just adds
to another with another IP
• NOTE: when connecting to a USER DEFINED network, the address can be assigned
with --ip=[IP]
• docker network ls
- 29 -
Title J. Titleski Linux Academy + Cloud Assessments
• --format=“{{.NetworkSettings.Networks.[network name].IPAddress}}”
• cleanly display the network IP address for the given network name and container
• --gateway=[IP]
• com.docker.network.bridge.name
• com.docker.network.bridge.enable_ip_masquerade
• com.docker.network.bridge.enable_icc
• com.docker.network.bridge.host_binding_ipv4
• com.docker.network.driver.mtu
• cat /etc/resolv.conf
• will remap the indicated host port to the indicated container port for accessing the
container service
• -P
• will map A host port (above 32000) to the default container exposed port
• docker container ps
• will list characteristics of running container including ports and port mapping
• --format=“{{.NetworkSettings.Networks.[network driver].IPAddress}}”
• for container IP
• --format=“{{.NetworkSettings.Ports}}”
• --driver=overlay
• --subnet=[network/mask]
• --gateway=[IP]
- 31 -
Title J. Titleski Linux Academy + Cloud Assessments
• --network=[network name]
• run on any host once deployed with instance, will show the instance information
for IP on that network
• NOTE: underlying hosts will not be able to see/interact with the new overlay network
• docker ps
- 32 -
Title J. Titleski Linux Academy + Cloud Assessments
• docker volume ls
• for characteristics
• --mount [source=/path],target=[path]
• /var/lib/docker/volumes/[volumename]/_data
• cannot share the underlying volume (each instance uses its own storage)
• NOTE: Docker for AWS and Azure do support shared storage using the ‘Cloudstor’
plugin
• removes objects
• volumes
- 33 -
Title J. Titleski Linux Academy + Cloud Assessments
• containers
• images
• networks
• build caches
• export DOCKER_CONTENT_TRUST=1
• advantage of shell export is just for THAT shell environment, allowing flexibility
• builds of content then (Dockerfiles) will need to have it explicitly disabled to build
successfully
• docker build
• --disable-content-trust
• push the trusted content (which will create the required signature keys, creating them if
needed on first push)
• UCP INSTALL
• on manager node
• obtain Docker EE free 30 day trial license from store.docker.com, download to system
with browser
• /etc/hosts
• DTR INSTALL
• `docker run -it --rm docker/dtr install --ucp-node tcox5.mylabserver.com \ - where the
DTR is going to be --ucp-username admin --ucp-url https://tcox4.mylabserver.com
\ - where UCP itself is --ucp-insecure-tls` - trust the certs that are used
• same login/password
• NOTE: UCP will be offline during backup but it will NOT affect running services
- 35 -
Title J. Titleski Linux Academy + Cloud Assessments
• --passphrase [passphrase]
• DTR
• NOTE: DTR will be offline during backup and will not be available for pulls/pushes at
that time
- 36 -