Skip to content

Docker Cheat Sheet

Christoph Diehl edited this page Oct 31, 2018 · 10 revisions

Used Docker version: 18.03.1-ce

Table of Contents

Basic Workflow

Repository Managment

docker login | search | pull | push | logout

Search

docker search python

Images

docker pull python

List

docker images
docker images -a        # Show intermediate images too.
docker images -a -q     # Show only the image IDs.

Remove

Whenever you assign a tag that is already in use to a new image, the old image with that tag will stay around. i.e re-building an image with the same tag.

docker image prune
docker image prune --all
docker rmi $(docker images -q -f dangling=true)
docker rmi $(docker images -q -a)

Layers

Each Layer has an ID and a pointer to the parent Layer.

History

docker history python

Dockerfile Instructions

Build

docker build --pull --squash -t <repository/name:version> -t <repository/name:latest> .

Publish

docker login --username=<username>
docker push repository/name:version

Containers

Run

docker run -it --rm python
docker run -it --rm python python -c "print('snakebyte')"
docker run -it --rm --entrypoint=/bin/bash python
docker run -d -it ubuntu
docker exec <id> <command>
docker attach <id>

List

docker ps           # Show running containers only.
docker ps -a        # Show stopped containers too.
docker ps -a -q     # Show only the container IDs.

Stop

docker stop $(docker ps -q)

Remove

docker container prune
docker rm -v $(docker ps -q -f status=exited)
docker rm -v $(docker ps -q -a)

Volumes

docker run -it -v ~/documents/:/data ubuntu
docker volume ls
docker run -it -v /data ubuntu
docker volume ls
docker volume inspect <volume_name_from_ls>

Volumes between containers

docker run -it --name ubuntu -v /data ubuntu
docker run -it --name busybox --volumes-from ubuntu busybox

Data-only containers

docker create -v ~/nginx/html:/usr/share/nginx/html --name data nginx
docker run --name docker-nginx -p 80:80 -d --volumes-from data nginx
docker volume create --name data
docker run -it -v data:/data ubuntu

List

docker volume ls
docker volume ls -f dangling=true

Remove

docker volume prune
docker volume rm $(docker volume ls -qf dangling=true)

There are volume drive plugins available for Docker.

Networking

Expose Ports

docker run -p <container_port><host_port> <image_name>
docker run --name nginx -d -p 8080:80 nginx
docker port nginx
docker stop nginx

Ports: Either <container:host> or container only. In the latter case a random port will be choosen on the host.

Expose: Won't be published to the host machine and are only accessible to linked services. A common usage would be with docker-compose.

Both variations support ranges in the form of <start>-<end>.

Linking Containers

docker run --name mysql -e MYSQL_ROOT_PASSWORD=foobar -it mysql
docker run -it --name ubuntu --link mysql:mysql ubuntu

Run more /etc/hosts in the second run command.

Run env | grep MYSQL_ in the second run command. These environment variables got shared.

Network Types

Standard: none, host and bridge (default)

docker network ls
docker run --net=none busybox
docker inspect --format '{{ .NetworkSettings.IPAddress }}' <name|id>

Creating a new network between containers

docker network create <name>
docker run -it --name container1 --net=<name> <image1>
docker run -it --net=container:container1 <image2>     # Run in same network as image1

Run ping container1 in the second run command.

Insights

Container

docker inspect <name|id>
docker inspect --format '{{ .State.ExitCode }}' <name|id>
docker inspect --format '{{ .LogPath }}' <name|id>
docker inspect --format '{{ .State.Pid}}' <name|id>
docker logs --follow <name|id>
docker logs --since 60m <name|id>
docker stats ---no-stream
docker system df

Data Manament Commands

docker system|volume|network|container|image --help
docker system|volume|network|container|image prune
docker exec <name|id> dpkg -l    # Show installed packages.

Healthcheck

Dockerfile

HEALTHCHECK --interval=5s --timeout=3s CMD curl --fail http://localhost:8000 || exit 1

Bash

docker run -d -it --health-cmd "curl --fail http://localhost:8000 || exit 1" <name|id>

Inspect

docker inspect --format "{{json .State.Health}}" db

Disable

docker run -d -it --no-healthcheck=true <name|id>

Constraints

User memory

docker update
    --memory 1G                # hard limit
    --memory-reservation 500M  # soft limit, docker attempts to shrink to be below
    <name|id>

Kernel memory

docker update
    --kernel-memory 100M       # implicit process spawnage control
    <name|id>

CPU

docker update
    --cpu-quota=25000
    --cpus 2
    --cpu-shares 512
    <name|id>

Restart Policies

--restart=no
--restart=always             # regardless of exit code
--restart=unless-stopped     # regardless of exit code but not on daemon startup
--restart=on-failure:N       # whenever container exists with non-zero exit code

Default: no

Credentials

Docker supports platform key managers.

$HOME/.docker/config.json

"auths": {
    "https://index.docker.io/v1/": {}
},
"credsStore": "osxkeychain"

Docker Compose

docker-compose.yml

version: '3'
services:
    frontend:
        build: frontend
        ports:
            - "5000:5000"
        volumes:
            - ./frontend:/frontend
        links:
            - redis
    redis:
        image: "redis:alpine"
docker-compose up

REST API for Docker HUB

curl -H "Content-Type: application/json" \
     -X POST
     -d '{"email": "user@host.com", "username": "foo", "password": "bar"}'
     https://registry.hub.docker.com/v1/users

Personal Registry

docker run -d -p 5000:5000 --restart always --name registry registry:2
docker login --username <user> --password <pass> localhost:5000
docker pull ubuntu
docker tag ubuntu localhost:5000/<name>
docker push localhost:5000/<name>
docker image remove ubuntu
docker image remove localhost:500/<name>
docker pull localhost:5000/<name>

Reference: https://github.com/docker/docker.github.io/blob/master/registry/deploying.md

Security Considerations

--pids-limit=64                       # Limit the number of active processes.
--security-opt=no-new-privileges      # Prevent processes from gaining new privs.
-v $(pwd)/secrets:/secrets:ro <image> # Set volumes to be read-only.
--read-only                           # Set the container to be read-only.
--icc=false --iptables                # Disable Inter-Container-Communication.

Best practices for deploying containers in production

docker run -it --net host --pid host --userns host --cap-add audit_control \
    -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
    -v /var/lib:/var/lib \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /usr/lib/systemd:/usr/lib/systemd \
    -v /etc:/etc --label docker_bench_security \
    docker/docker-bench-security

Reference: https://github.com/konstruktoid/Docker/blob/master/Security/CheatSheet.adoc

Add a User account

RUN groupadd -r user && useradd -r -g user user
USER user

Disable setuid permissions

RUN find / -perm +6000 -type f -exec chmod a-s {} \; || true

Tricks

docker run -d <image> tail -f /dev/null  # Keep container running.
docker run --pid=host                    # Uses the hosts PID namespace inside the container.
docker run --pid=container:id            # Merges the PID namespace of another container.
docker run --log-driver=syslog ubuntu

Heredoc

docker build -t htop - << EOF
FROM alpine
RUN apk --no-cache add htop
EOF

Connect to xhyve

screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
ntpd -d -q -n -p pool.ntp.org

Sharing

TTY #1:

docker run -it /bin/bash
<configure>

TTY #2:

docker ps
docker export <id> > image.tar

User:

docker import - < image.tar

Tools

References