You are on page 1of 46

Getting Started

create & run

Create a container and run it in the background


$ docker run -d -p 80:80 docker/getting-started

• -d - Run the container in detached (background) mode


• -p 80:80 - Map port 80 to port 80 in the container, format: host port: container port
• docker/getting-started - the mirror to use

docker run = docker create + docker start


docker create <image name>
docker run <container id>

Create and run the container in the foreground (if you want to exit the container but not close the container, press Ctrl+P+Q)
$ docker run -it --rm -p 8001:8080 --name my-nginx nginx

• -it - Interactive bash mode


• --rm - Automatically delete container files after the container terminates
• -p 8001:8080 - maps 8001 the port to 8080 the port in the container
• --name my-nginx - specify a name
• nginx - the mirror to use
docker run -d -t -i -e REDIS_NAMESPACE='staging' \
-e POSTGRES_ENV_POSTGRES_PASSWORD='foo' \
-e POSTGRES_ENV_POSTGRES_USER='bar' \
-e POSTGRES_ENV_DB_NAME='mysite_staging' \
-e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' \
-e SITE_URL='staging.mysite.com' \
-p 80:80 \
--link redis:redis \
--name container_name dockerhub_id/image_name
general commands
docker ps list running containers
docker ps -a list all containers
docker ps -s list running containers with cpu/memory usage statistics
docker images list all available mirrors
docker exec -it <container> bash
connect to a running container using bash shell
docker exec -it <container> <command>

docker logs <container> show the console log of a container


docker stop <container> stop a running container
docker restart<container> restart a running container
docker rm <container> remove a container
docker port <container> show the port mapping of a container
docker top <container> list the processes running in a container
docker kill <container> forcefully stop a running container
parameter <container> can be either the container id or name
Container Management
start & stop
start the container
docker start <container> <command> -a, --attach
--detach-keys string
Attach STDOUT/STDERR and forward signals
Override the key sequence for detaching a container
-i, --interactive Attach container's STDIN

docker stop <container> stop the container


docker restart <container> restart the container
docker pause <container> pause the container
docker unpause <container> unpause the container
docker wait <container> block until the container stops running
docker kill <container> send sigkill signal to the container
docker attach <container> attach to the running container

stats
docker ps list the running containers
docker ps -a list all containers, including stopped ones
docker logs <container> show the logs of the container
docker inspect <container> display detailed information about the container
docker events <container> show the events related to the container
docker port <container> show the public port of the container
docker top <container> display the running processes inside the container
docker stats <container> show the resource usage of the container
docker diff <container> show the changes made to the container

create a container
docker create [options] IMAGE
-a, --attach # Attach standard output/errors
-i, --interactive # append standard input (interactive)
-t, --tty # pseudo-terminal pseudo-tty
--name NAME # Name your image
-p, --publish 5000:5000 # Port mapping (host:container)
--expose 5432 # Expose the port to the container
-P, --publish-all # Publish all ports
--link container:alias # link linking
-v, --volume `pwd`:/app # mount (absolute path required)
-e, --env NAME=hello # environment variables env vars

example
$ docker create --name my-container -p 8080:80 nginx

control
docker rename <old-name> <new-name> rename container
docker rm <container> remove container
docker update --cpu-shares 512 -m 300M <container> update container
Docker Images
general
docker images list all docker images
docker pull [image-name] pull a docker image from a registry
docker build [options] [path] build a docker image from a dockerfile
docker push [image-name] push a docker image to a registry
docker tag [image-name] [new-image-name] add a new tag to a docker image
docker rmi [image-name] remove a docker image
docker save [image-name] -o [path/to/save] save a docker image to a tar archive
docker load -i[path/to/archive] load a docker image from a tar archive
docker history [image-name] show the history of a docker image
docker inspect [image-name] display low-level information on a docker image
docker search [search-term] search for docker images on docker hub
docker commit[container-name] [new-image-name] create a new docker image from a container
docker import [url] [new-image-name] create a new docker image from a remote file
docker image prune remove all dangling (unused) images
build image
# Build an image from a Dockerfile located in the current directory
docker build -t my-image .

# Build an image from a Dockerfile located in a specific directory


docker build -t my-image /path/to/Dockerfile/directory

# Build an image with a specific tag


docker build -t my-username/my-image:1.0 .

# Build an image with build arguments


docker build -t my-image --build-arg MY_ARG=value .

# Build an image with a custom Dockerfile name


docker build -t my-image -f Dockerfile.custom .

# Build an image from a Dockerfile located in a specific GitHub repository


docker build github.com/creack/docker-firefox

# Build an image from a Dockerfile passed via STDIN


docker build - < Dockerfile

# Build an image from a context passed via STDIN


docker build - < context.tar.gz

# Build an image with a specific tag


docker build -t eon/nginx-server .

# Build an image from a different Dockerfile than the default


docker build -f myOtherDockerfile .

# Build an image from a remote Dockerfile


curl example.com/remote/Dockerfile | docker build -f - .
remove all

$ docker rmi -f $(docker images | grep "none" | awk '{print $3}')

This command will remove all Docker images on your machine that are not currently being used by any containers. Here's how it works:
• docker images lists all Docker images on the host machine.
• grep "none" filters the output to show only images with the tag "none". These images are usually created when a new image is built, and the old
image with the same name and tag is still present on the machine.
• awk '{print $3}' extracts the third column from the output, which is the image ID.
• $() is a command substitution that passes the output of the previous command as input to docker rmi -f. The -f option forces the removal of the
specified image(s).
Docker Network
operate

docker network ls list all docker networks


docker network create [network-name] create a new docker network
docker network rm [network-name] remove a docker network
docker network inspect [network-name] display detailed information on a docker network
docker network connect [network-name] [container-name] connect a container to a docker network
docker network disconnect [network-name] [container-name] disconnect a container from a docker network
docker network prune remove all unused docker networks
docker network create --driver overlay [network-name] create a docker swarm overlay network
docker network create --driver bridge --subnet [subnet]
create a bridge network with a specified subnet
[network-name]
docker network create --driver macvlan --subnet [subnet] -o create a mac vlan network with a specified subnet and
parent=[interface-name] [network-name] parent interface

create a network
docker network create -d overlay OverlayNetwork
docker network create -d bridge BridgeNetwork
docker network create -d overlay \
--subnet=192.168.0.0/16 \
--subnet=192.170.0.0/16 \
--gateway=192.168.0.100 \
--gateway=192.170.0.100 \
--ip-range=192.168.1.0/24 \
--aux-address="my-router=192.168.1.5" \
--aux-address="my-switch=192.168.1.6" \
--aux-address="my-printer=192.170.1.5" \
--aux-address="my-nas=192.170.1.6" \
OverlayNetwork

• --subnet - Defines one or more subnets for the network.


• --gateway - Defines one or more gateways for the network.
• --ip-range - Defines a range of IP addresses that can be assigned to containers on the network.
• --aux-address - Defines additional IP addresses that can be assigned to containers on the network.
Miscellaneous

Docker Hub

docker login login to docker hub


docker logout logout from docker hub
docker search [search-term] search for docker images on docker hub
docker pull [image-name] pull a docker image from docker hub
docker push [image-name] push a docker image to docker hub
docker tag [local-image] [username/image-name:tag] tag a local docker image for upload to docker hub
docker push [username/image-name:tag] push a tagged docker image to docker hub
build and tag a docker image with a dockerfile, then push it to
docker build -t [username/image-name:tag] .
docker hub
docker logout [registry] log out from a specific registry
docker search --filter "is-official=true" [search-term] search for official docker images
docker search --filter "is-automated=true" [search-term] search for automated docker images
docker system prune -a remove all unused images and cache on the host machine
Mirror a repository

To log in to the mirror warehouse:


docker login
docker login localhost:8080

To log out of the mirror repository:


docker logout
docker logout localhost:8080

To search for a mirrored image:


docker search nginx
docker search nginx --stars=3 --no-trunc busybox

To pull a mirrored image:


docker pull nginx
docker pull eon01/nginx
docker pull localhost:5000/myadmin/nginx

To push a mirrored image:


docker push eon01/nginx
docker push localhost:5000/myadmin/nginx
Docker Compose
docker-compose up - create and start containers defined in a docker-compose.yml file
docker-compose up -d - … in background
docker-compose up --build - … rebuild images
docker-compose down stop and remove containers, networks, and volumes created by docker-compose up
docker-compose build build or rebuild services defined in a docker-compose.yml file
docker-compose start start existing containers defined in a docker-compose.yml file
docker-compose stop stop existing containers defined in a docker-compose.yml file
docker-compose restart restart containers defined in a docker-compose.yml file
docker-compose logs view output from containers defined in a docker-compose.yml file
docker-compose ps list containers defined in a docker-compose.yml file
docker-compose config validate and view the compose file
docker-compose pull pull images for services defined in a docker-compose.yml file
docker-compose run run a one-off command on a service defined in a docker-compose.yml file
docker-compose kill force stop containers defined in a docker-compose.yml file
docker-compose rm remove stopped containers defined in a docker-compose.yml file
docker-compose exec run a command in a running container
docker-compose up --scale [service-name]=n scale a service to n instances
docker-compose top display the running processes of a container
docker-compose scale <service_name>=<replica> specify the number of containers for the service
docker-compose run -rm -p 2022:22 web bash start the web service and run bash as its command, remove the old container

Docker Services
docker service create create a new docker service in a docker swarm cluster
docker service ls list all docker services running in a docker swarm cluster
docker service inspect display detailed information on a docker service running in a docker swarm cluster
docker service update update a docker service running in a docker swarm cluster
docker service rm remove a docker service running in a docker swarm cluster
docker service scale scale the number of replicas in a docker service running in a docker swarm cluster
docker service logs view the logs of a docker service running in a docker swarm cluster
docker service ps list the tasks in a docker service running in a docker swarm cluster
docker service create --network create a docker service in a specific network in a docker swarm cluster
docker service create --replicas create a docker service with a specified number of replicas in a docker swarm cluster
docker service create --mount mount a volume to a docker service running in a docker swarm cluster
docker service create --constraint set placement constraints for a docker service running in a docker swarm cluster
docker service create --env set environment variables for a docker service running in a docker swarm cluster
docker service create --label add metadata labels to a docker service running in a docker swarm cluster
docker service create --mode set the update strategy for a docker service running in a docker swarm cluster
docker service create --health-cmd set a health check command for a docker service running in a docker swarm cluster

Docker Stack

docker stack deploy deploy a new docker stack


docker stack ls list all docker stacks
docker stack ps list the tasks in a docker stack
docker stack services list the services in a docker stack
docker stack rm remove a docker stack
docker stack deploy --compose-file deploy a docker stack using a compose file
docker stack deploy --with-registry-auth deploy a docker stack and authenticate with a private registry
docker stack deploy --prune remove any old services that are no longer part of the docker stack
docker stack deploy --resolve-image always always attempt to resolve the latest version of an image
docker stack deploy --orchestrator kubernetes deploy a docker stack as a kubernetes service

Note that some of these commands are specific to Docker Swarm mode, which is a feature of Docker that allows you to run Docker in a clustered mode.
Other commands, such as the --orchestrator kubernetes option, are specific to deploying Docker stacks to a Kubernetes cluster.
Docker Machine
docker-machine create --driver virtualbox myvm1 create a virtual machine with the virtualbox driver named myvm1
docker-machine create -d hyperv --hyperv-virtual-switch create a virtual machine with the hyper-v driver named myvm1
"myswitch" myvm1 using the myswitch virtual switch
docker-machine env myvm1 display basic information about the myvm1 virtual machine
docker-machine ssh myvm1 "docker node ls" list the nodes in your cluster on the myvm1 virtual machine
docker-machine ssh myvm1 "docker node inspect <node ID>" inspect nodes on the myvm1 virtual machine
docker-machine ssh myvm1 "docker swarm join-token -q
view the join token on the myvm1 virtual machine
worker"
open an ssh session with the myvm1 virtual machine; exit the
docker-machine ssh myvm1
session by typing "exit"
docker-machine ssh myvm2 "docker swarm leave" let workers leave the swarm on the myvm2 virtual machine
let the master leave and kill the swarm on the myvm1 virtual
docker-machine ssh myvm1 "docker swarm leave -f"
machine
docker-machine start myvm1 start the myvm1 virtual machine if it is not running
docker-machine stop $(docker-machine ls -q) stop all running virtual machines
docker-machine rm $(docker-machine ls -q) delete all virtual machines and their disk images
copy the docker-compose.yml file to the home directory of the
docker-machine scp docker-compose.yml myvm1:~
myvm1 virtual machine
docker-machine ssh myvm1 "docker stack deploy -c <file> deploy an application on the myvm1 virtual machine using the
<app>" specified compose file and app name

Main Commands
attach attaches local standard input, output, and error streams to a running container
build builds images from dockerfile
commit creates a new image from container changes
cp copies files/folders between the container and the local filesystem
create creates a new container
diff checks for changes to files or directories on the container filesystem
events gets live events from the server
exec runs a command in the running container
export exports the container's filesystem to a tar archive
history shows the history of the image
images lists the images
import imports the contents from tarball to create a file system image
info displays system-wide information
inspect returns low-level information about docker objects
kill kills one or more running containers
load loads an image from a tar archive or stdin
login logs in to the docker registry
logout logs out from the docker registry
logs gets logs of containers
pause suspends all processes in one or more containers
port lists the container's port mappings or specific mappings
ps lists containers
pull pulls a mirror or repository from the registry
push pushes the image or repository to the registry
rename renames a container
restart restarts one or more containers
rm removes one or more containers
rmi removes one or more mirrors
run runs a command in a new container
save saves one or more images to a tar archive (streams to stdout by default)
search searches for images in docker hub
start starts one or more stopped containers
stats shows a live stream of container resource usage statistics
stop stops one or more running containers
tag creates a tag that references SOURCE_IMAGE TARGET_IMAGE
top displays the running processes of a container
unpause unpauses all processes in one or more containers
update updates the configuration of one or more containers
version displays docker version information
wait blocks until one or more containers stop, then prints their exit codes

Run/Create Options
--add-host list # Add a custom host to the IP map (host:ip)
-a, --attach list # Connect to STDIN, STDOUT or STDERR
--blkio-weight uint16 # block IO (relative weight), between 10 and 1000, or 0 disabled (default 0)
--blkio-weight-device list # Block IO weights (relative device weights) (default [])
--cap-add list # Add Linux functions
--cap-drop list # Drop Linux functions
--cgroup-parent string # Optional parent cgroup of the container
--cgroupns string # The Cgroup namespace to use (host|private)
# 'host': cgroup namespace of the Docker host to run the container in
# 'private': run the container in its own private cgroup namespace
# '': use the
# default-cgroupns-mode option (default)
--cidfile string # Write the container ID to a file
--cpu-period int # Limit CPU CFS (Completely Fair Scheduler) periods
--cpu-quota int # Limit CPU CFS (full fair scheduler) quota
--cpu-rt-period int # Limit CPU real-time cycles in microseconds
--cpu-rt-runtime int # Limit CPU realtime runtime in microseconds
-c, --cpu-shares int # CPU shares (relative weights)
--cpus decimal # Number of CPUs
--cpuset-cpus string # CPUs allowed to execute (0-3, 0,1)
--cpuset-mems string # MEMs allowed to execute (0-3, 0,1)
--device list # Add the host device to the container
--device-cgroup-rule list # Add the rule to the list of devices allowed by the cgroup
--device-read-bps list # Limit the read rate (bytes per second) of the device (default [])
--device-read-iops list # Limit the read rate (IOs per second) of the device (default [])
--device-write-bps list # Limit the write rate of the device (bytes per second) (default [])
--device-write-iops list # Limit the write rate of the device (IO per second) (default [])
--disable-content-trust # Skip image verification (default true)
--dns list # Set custom DNS servers
--dns-option list # Set DNS options
--dns-search list # Set custom DNS search domains
--domainname string # Container NIS domain name
--entrypoint string # Override the default entry point of the mirror
--e, --env list # Set environment variables
--env-file list # Read in environment variable files
--expose list # expose a port or series of ports
--gpus gpu-request # GPU devices to add to the container ("all" to pass all GPUs)
--group-add list # Add other groups to join
--health-cmd string # Command to run to check operational status
--health-interval duration # Time (ms|s|m|h) between run checks (default 0s)
--health-retries int # Need to report unhealthy consecutive failures
--health-start-period duration # Start time (ms|s|m|h) for container initialization before starting the health retry countdown (default 0s)
--health-timeout duration # The maximum time (ms|s|m|h) allowed to run a check (default 0s)
--help # Print the use of
-h, --hostname string # The container host name
--init # Run an init inside the container to forward signals and harvest processes
--i, --interactive # Keep STDIN open even if there is no connection
--ip string # IPv4 address (e.g. 172.30.100.104)
--ip6 string # IPv6 address (e.g., 2001:db8::33)
--ipc string # The IPC mode to use
--isolation string # Container isolation technology
--kernel-memory bytes # Kernel memory limit
-l, --label list # Set metadata on the container
--label-file list # Read in line delimited label files
--link list # Add a link to another container
--link-local-ip list # container IPv4/IPv6 link local address
--log-driver string # The container's logging driver
--log-opt list # Logging driver options
--mac-address string # MAC address of the container (e.g. 92:d0:c6:0a:29:33)
-m, --memory bytes # Memory limit
--memory-reservation bytes # Memory soft limit
--memory-swap bytes # Swap limit equal to memory plus swap: '-1' Enable unlimited swap
--memory-swappiness int # Adjust container memory swapping (0 to 100) (default -1)
--mount mount # Attach a filesystem mount to the container
--name string # Assign a name to the container
--network network # Connect the container to the network
--network-alias list # Add network-wide aliases to the container
--no-healthcheck # Disable any container-assigned HEALTHCHECK
--oom-kill-disable # Disable OOM killers
--oom-score-adj int # Adjust the host's OOM preferences (-1000 to 1000)
--pid string # The PID namespace to use
--pids-limit int # Adjust container pids limit (set -1 for no limit)
--platform string # Set the platform if the server supports multiple platforms
--privileged # Grant extended privileges to this container
-p, --publish list # Publish the container's ports to the host
-P, --publish-all # Publish all exposed ports to random ports
--pull string # Pull mirrors ("always"|"missing"|"never") before creation (default "missing")
--read-only # Mount the container's root filesystem as read-only
--restart string # Restart policy to apply when the container exits (default "no")
--rm # Automatically remove the container when it exits
--runtime string # Runtime for this container
--security-opt list # Security options
--shm-size bytes # size of /dev/shm
--stop-signal string # Signal to stop the container (default "SIGTERM")
--stop-timeout int # Timeout to stop the container (in seconds)
--storage-opt list # Storage driver options for the container
--sysctl map # Sysctl options (default map[])
--tmpfs list # Mount tmpfs directory
-t, --tty # Assign a pseudo TTY
--ulimit ulimit # ulimit option (default [])
--u, --user string # Username or UID (format: <name|uid>[:<group|gid>])
--userns string # The user namespace to use
--uts string # The UTS namespace to use
--v, --volume list # Bind the mounted volumes
--volume-driver string # Optional volume driver for the container
--volumes-from list # Mount volumes from the specified container
-w, --workdir string # The working directory inside the container
Global Parameters
--config path Location of client config files (default "~/.docker")
--context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with
"docker context use")
-c, --context string Alias for --context
-D, --debug Enable debug mode
-H, --host list Daemon socket(s) to connect to
-l, --log-level string Set the logging level ("debug", "info", "warn", "error", "fatal") (default "info")
--tls Use TLS; implied by --tlsverify
--tlscacert string Trust certs signed only by this CA (default "~/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "~/.docker/cert.pem")
--tlskey string Path to TLS key file (default "~/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Docker Examples
Docker Portainer
$ docker volume create portainer_data

$ docker run -d -p 8000:8000 -p 9000:9000 --name portainer --restart always -v

/var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce

• This will create a Docker volume for Portainer's data and start the Portainer container, exposing ports 8000 and 9000 for web access and mapping
the Docker daemon's socket to the container.
• Once the Portainer container is running, you can access the web interface by navigating to http://localhost:9000 in your web browser.
You will be prompted to create an initial administrator account. Once you have done that, you can start managing your Docker environment through
Portainer's web interface.
Portainer provides a graphical user interface that allows you to manage your Docker containers, images, volumes, and networks and manage users, teams,
and roles. For example, you can easily create and deploy new containers, inspect and manage existing containers, view logs and resource usage, and
perform container backups and restores.
Code Server
First, you need to create a Dockerfile to build the Code Server image:
FROM codercom/code-server:latest
USER root
RUN apt-get update && \
apt-get install -y build-essential && \
apt-get clean
USER coder

This Dockerfile uses the latest version of the Code Server image and installs the build-essential package for compiling and building code. It also sets the
user to coder to avoid running Code Server as the root user.

Once you have created the Dockerfile, you can build the Code Server image using the docker build command:
$ docker build -t my-code-server .

This will build the image and tag it with the name my-code-server.

Once the image is built, you can start a new container by running the following command:
$ docker run -it -p 127.0.0.1:8080:8080 my-code-server

Code Server provides a full-featured code editor that supports multiple programming languages and extensions. You can create and edit files, run code,
debug, and even collaborate with others in real-time.

MySQL
$ docker run --name mysql \
-p 3306:3306 \
-v $HOME/mysql/conf.d:/etc/mysql/conf.d \
-v $HOME/mysql/data:/var/lib/mysql \
-v /etc/localtime:/etc/localtime:gb \
-e MYSQL_ROOT_PASSWORD=54321 \
-d mysql:5.8.23

Redis
$ docker run -d --name myredis \
-v $HOME/redis/conf:/usr/local/etc/redis \
-v /etc/localtime:/etc/localtime:gb \
redis redis-server /usr/local/etc/redis/redis.conf

nginx
$ docker run --name my-nginx \
-v "$HOME/nginx/nginx.conf:/etc/nginx/nginx.conf:ro" \
-v "$HOME/nginx/html:/usr/share/nginx/html:ro" \
-p 8080:80 \
-d nginx

PostgreSQL
$ docker run --name my-postgres \
-e POSTGRES_PASSWORD=mysecretpassword \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v $HOME/nginx/mount:/var/lib/postgresql/data \
-d postgres

Dim
$ docker run --name my-dim \
-p 8000:8000/tcp \
-v $HOME/.config/dim:/opt/dim/config \
-v $HOME/dim/media:/media:ro \
-d ghcr.io/dusk-labs/dim:dev

Gitlab
$ docker run -d --name gitlab \
--hostname gitlab.example.com \
--publish 8443:443 --publish 8081:80 -p 2222:22 \
--restart always \
--volume $HOME/gitlab/config:/etc/gitlab \
--volume $HOME/gitlab/logs:/var/log/gitlab \
--volume $HOME/gitlab/data:/var/opt/gitlab \
-v /etc/localtime:/etc/localtime \
--shm-size 256m \
gitlab/gitlab-ce:latest
Dockerfile
FROM
Usage:
FROM <image>
FROM <image>:<tag>
FROM <image>@<digest>

Information:
• FROM must be the first non-comment instruction in the Dockerfile.
• FROM can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last image ID output by the
commit before each new FROM command.
• The tag or digest values are optional. If you omit either of them, the builder assumes a latest by default. The builder returns an error if it
cannot match the tag value.

MAINTAINER
Usage:
MAINTAINER <name>

The MAINTAINER instruction allows you to set the Author field of the generated images.

RUN
Usage:
RUN <command> #(shell form, the command is run in a shell, which by default is
/bin/sh -c on Linux or cmd /S /C on Windows)
RUN ["<executable>", "<param1>", "<param2>"] #(exec form)

Information:
• The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain the specified shell
executable.
• The default shell for the shell form can be changed using the SHELL command.
• Normal shell processing does not occur when using the exec form. For example, RUN ["echo", "$HOME"] will not do variable substitution on
$HOME.
CMD
Usage:
CMD ["<executable>","<param1>","<param2>"] #(exec form, this is the preferred form)
CMD ["<param1>","<param2>"] #(as default parameters to ENTRYPOINT)
CMD <command> <param1> <param2> #(shell form)

Information:
• The main purpose of a CMD is to provide defaults for an executing container. These defaults can include an executable, or they can omit the
executable, in which case you must specify an ENTRYPOINT instruction as well.
• There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.
• If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified
with the JSON array format.
• If the user specifies arguments to docker run then they will override the default specified in CMD.
• Normal shell processing does not occur when using the exec form. For example, CMD ["echo", "$HOME"] will not do variable substitution on
$HOME.
LABEL
Usage:
LABEL <key>=<value> [<key>=<value> …]

Information:
• The LABEL instruction adds metadata to an image.
• To include spaces within a LABEL value, use quotes and backslashes as you would in command-line parsing.
• Labels are additive including LABELs in FROM images.
• If Docker encounters a label/key that already exists, the new value overrides any previous labels with identical keys.
• To view an image’s labels, use the docker inspect command. They will be under the "Labels" JSON attribute.

EXPOSE
Usage:
EXPOSE <port> [<port> …]

Information:
• Informs Docker that the container listens on the specified network port(s) at runtime.
• EXPOSE does not make the ports of the container accessible to the host.

ENV
Usage:
ENV <key> <value>
ENV <key>=<value> [<key>=<value> …]

Information:
• The ENV instruction sets the environment variable <key> to the value <value>.
• The value will be in the environment of all “descendant” Dockerfile commands and can be replaced inline as well.
• The environment variables set using ENV will persist when a container is run from the resulting image.
• The first form will set a single variable to a value with the entire string after the first space being treated as the <value> - including characters
such as spaces and quotes.
ADD
Usage:
ADD <src> [<src> ...] <dest>
ADD ["<src>", ... "<dest>"] #(this form is required for paths containing whitespace)

Information:
• Copies new files, directories, or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>.
• <src> may contain wildcards and matching will be done using Go’s filepath.Match rules.
• If <src> is a file or directory, then they must be relative to the source directory that is being built (the context of the build).
• <dest> is an absolute path, or a path relative to WORKDIR.
• If <dest> doesn’t exist, it is created along with all missing directories in its path.
COPY
Usage:
COPY <src> [<src> ...] <dest>
COPY ["<src>", ... "<dest>"] #(this form is required for paths containing whitespace)

Information:
• Copies new files or directories from <src> and adds them to the filesystem of the image at the path <dest>.
• <src> may contain wildcards and matching will be done using Go’s filepath.Match rules.
• <src> must be relative to the source directory that is being built (the context of the build).
• <dest> is an absolute path, or a path relative to WORKDIR.
• If <dest> doesn’t exist, it is created along with all missing directories in its path.
ENTRYPOINT
Usage:
ENTRYPOINT ["<executable>", "<param1>", "<param2>"] #(exec form, preferred)
ENTRYPOINT <command> <param1> <param2> #(shell form)

Information:
• Allows you to configure a container that will run as an executable.
• Command line arguments to docker run <image> will be appended after all elements in an exec form ENTRYPOINT and will override all
elements specified using CMD.
• The shell form prevents any CMD or run command line arguments from being used, but the ENTRYPOINT will start via the shell. This means the
executable will not be PID 1 nor will it receive UNIX signals. Prepend exec to get around this drawback.
• Only the last ENTRYPOINT instruction in the Dockerfile will have an effect.

VOLUME
Usage:
VOLUME ["<path>", ...]
VOLUME <path> [<path> …]

Creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers.

USER
Usage:
USER <username | UID>

The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the
Dockerfile.

WORKDIR
Usage:
WORKDIR </path/to/workdir>

Information:
• Sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow it.
• It can be used multiple times in the one Dockerfile. If a relative path is provided, it will be relative to the path of the previous WORKDIR instruction.
ARG
Usage:
ARG <name>[=<default value>]

Information:
• Defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg
<varname>=<value> flag.
• Multiple variables may be defined by specifying ARG multiple times.
• It is not recommended to use build-time variables for passing secrets like github keys, user credentials, etc. Build-time variable values are visible to
any user of the image with the docker history command.
• Environment variables defined using the ENV instruction always override an ARG instruction of the same name.
• Docker has a set of predefined ARG variables that you can use without a corresponding ARG instruction in the Dockerfile.
◦ HTTP_PROXY and http_proxy
◦ HTTPS_PROXY and https_proxy
◦ FTP_PROXY and ftp_proxy
◦ NO_PROXY and no_proxy
ONBUILD
Usage:
ONBUILD <Dockerfile INSTRUCTION>

Information:
• Adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be
executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.
• Any build instruction can be registered as a trigger.
• Triggers are inherited by the "child" build only. In other words, they are not inherited by "grand-children" builds.
• The ONBUILD instruction may not trigger FROM, MAINTAINER, or ONBUILD instructions.

STOPSIGNAL
Usage:
STOPSIGNAL <signal>

The STOPSIGNAL instruction sets the system call signal that will be sent to the container to exit. This signal can be a valid unsigned number that matches a
position in the kernel’s syscall table, for instance 9, or a signal name in the format SIGNAME, for instance SIGKILL.

HEALTHCHECK
Usage:
HEALTHCHECK [<options>] CMD <command>
#(check container health by running a command inside the container)
HEALTHCHECK NONE #(disable any healthcheck inherited from the base image)

Information:
• Tells Docker how to test a container to check that it is still working
• Whenever a health check passes, it becomes healthy. After a certain number of consecutive failures, it becomes unhealthy.
• The <options> that can appear are...
◦ --interval=<duration> (default: 30s)
◦ --timeout=<duration> (default: 30s)
◦ --retries=<number> (default: 3)
• The health check will first run interval seconds after the container is started, and then again interval seconds after each previous check
completes. If a single run of the check takes longer than timeout seconds then the check is considered to have failed. It takes retries
consecutive failures of the health check for the container to be considered unhealthy.
• There can only be one HEALTHCHECK instruction in a Dockerfile. If you list more than one then only the last HEALTHCHECK will take effect.
• <command> can be either a shell command or an exec JSON array.
• The command's exit status indicates the health status of the container.
◦ 0: success - the container is healthy and ready for use
◦ 1: unhealthy - the container is not working correctly
◦ 2: reserved - do not use this exit code
• The first 4096 bytes of stdout and stderr from the <command> are stored and can be queried with docker inspect.
• When the health status of a container changes, a health_status event is generated with the new status.
SHELL
Usage:
SHELL ["<executable>", "<param1>", "<param2>"]

Information:
• Allows the default shell used for the shell form of commands to be overridden.
• Each SHELL instruction overrides all previous SHELL instructions, and affects all subsequent instructions.
• Allows an alternate shell be used such as zsh, csh, tcsh, powershell, and others.

docker-compose
Basic example
# docker-compose.yml
version: '2'

services:
web:
build: # build from Dockerfile
context: ./Path
dockerfile: Dockerfile
ports:
- "5000:5000"
volumes:
- .:/code
redis:
image: redis
Building
web:
# build from Dockerfile
build: .
args: # Add build arguments
APP_HOME: app
build: # build from custom Dockerfile
context: ./dir
dockerfile: Dockerfile.dev
# build from image
image: ubuntu
image: ubuntu:14.04

image: tutum/influxdb
image: example-registry:4000/postgresql
image: a4bc65fd

Ports
ports:
- "3000"
- "8000:80" # host:container
# expose ports to linked services (not to host)
expose: ["3000"]
Commands
# command to execute
command: bundle exec thin -p 3000
command: [bundle, exec, thin, -p, 3000]

# override the entrypoint


entrypoint: /app/start.sh
entrypoint: [php, -d, vendor/bin/phpunit]

Environment variables
# environment vars
environment:
RACK_ENV: development
environment:
- RACK_ENV=development

# environment vars from file


env_file: .env
env_file: [.env, .development.env]
Dependencies
# makes the `db` service available as the hostname `database` (implies depends_on)
links:
- db:database
- redis

# make sure `db` is alive before starting


depends_on:
- db
# make sure `db` is healty before starting and db-init completed without failure
depends_on:
db:
condition: service_healthy
db-init:
condition: service_completed_successfully
Other options
# make this service extend another
extends:
file: common.yml # optional
service: webapp

volumes:
- /var/lib/mysql
- ./_data:/var/lib/mysql
# automatically restart container
restart: unless-stopped
# always, on-failure, no (default)

Advanced features
Labels
services:
web:
labels:
com.example.description: "Accounting web app"
DNS servers
services:
web:
dns: 8.8.8.8
dns:
- 8.8.8.8
- 8.8.4.4

Devices
services:
web:
devices:
- "/dev/ttyUSB0:/dev/ttyUSB0"

Healthcheck
# declare service healthy when `test` command succeed
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 40s
Hosts
services:
web:
extra_hosts:
- "somehost:192.168.1.100"

External links
services:
web:
external_links:
- redis_1
- project_db_1:mysql

Volume
# mount host paths or named volumes, specified as sub-options to a service
db:
image: postgres:latest
volumes:
- "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock"
- "dbdata:/var/lib/postgresql/data"

volumes:
dbdata:
Network
# creates a custom network called `frontend`
networks:
frontend:

External network
# join a pre-existing network
networks:
default:
external:
name: frontend

User
# specifying user
user: root

# specifying both user and group with ids


user: 0:0

You might also like