Skip to content

Instantly share code, notes, and snippets.

@MarcHeiden
Last active December 12, 2023 19:55
Show Gist options
  • Save MarcHeiden/b84e69597c86c08344c4d955c9a9bcdf to your computer and use it in GitHub Desktop.
Save MarcHeiden/b84e69597c86c08344c4d955c9a9bcdf to your computer and use it in GitHub Desktop.

Docker Essentials

> docker

> docker [COMMAND]

Comands

Command Description
version Get information about the docker engine version
info Get information about the docker engine
system df Get information about the disk usage used by the docker engine
<dockerObject> prune Remove unused instances of the specified docker object (e.g. image)
system prune [-a] [--volumes] Remove stopped containers, unused networks, dangling images and dangling build cache. -a removes all unused images. --volumes removes all unused volumes.
builder prune [-a] Remove dangling build cache. -a removes all unused build cache.
ps [-a] List running containers. -a lists all containers.
start <containerName> [-i] Start container. -i gives an interactive shell.
stop <containerName> Stop container
restart <containerName> Restart container
pause <containerName> Pause container
unpause <containerName> Unpause container
rm <containerName> [-f] Remove stopped container. -f forces removal for running containers.
rename <oldContainerName> <newContainerName> Rename container
docker cp <sourcePath> <containerName>:<destinationPathInsideContainer> Copy files into a container
images -a List all images
tag <imageTag> <newImageTag> Create new tag for images
rmi <imageName> Remove image
image prune [-a] Remove dangling images. -a removes all unused images.
pull <imageName> Download an image from a registry
push <imageName> Upload an image to a registry
image history <imageName> Get information about the image layers and the corresponding Dockerfile instructions
top <containerName> List running processes of a container
inspect <dockerObjectName> Get information about a docker object (e.g. Container, Image, Network...)
logs <contanerName> Get container logs
events Show all docker events until stopped with keyboard interrupt
stats <containerName> See what ressouces are used by docker container

> docker run

Create a new docker container from an image and run it

> docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Options

Option Description
-p <hostPorts>:<containerPorts> Map container ports to the host ports
-d Run a container in the background and print the container ID
--name <containerName> Set the name for the new container
--hostname <hostname> Set the container hostname
-v <pathWhereToMountInsideContainer> Mount an anonymous volume stored under /var/lib/docker/volumes in the container
-v <volumeName>:<pathWhereToMountInsideContainer> Mount a named volume stored under /var/lib/docker/volumes in the container
-v <source>:<pathWhereToMountInsideContainer> Bind mount a host directory in the container
--network <networkName> Connect a container to a network
-e <key>=<value> Set environment variables inside the container
-it Used to get an interactive shell
--restart <restartPolicy> Specify how or if the container should restart on exit:
restartPolicyDescription
no(default)Do not automatically restart the container when it exits.
on-failure[:max_retries]Restart only if the container exits with a non-zero exit status.
alwaysAlways restart the container regardless of the exit status.
unless-stoppedAlways restart the container regardless of the exit status,including on daemon startup, except if the container was put into a stopped state before the Docker daemon was stopped.
--rm Remove container when it stopps running
--entrypoint <command> Overwrite default container entrypoint specified in the Dockerfile

Examples

# Run a new container with mapped ports in the background
> docker run -d --name <containerName> -p 5678-5688:5678-5688 -p 22:22 <imageName>

> docker create

Create a new docker container

> docker create [OPTIONS] IMAGE [COMMAND] [ARG...]

Options

Same as for docker run

> docker exec

Run a command in a running container

> docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Options

Option Description
-it Used to get an interactive shell

Examples

# Open an interactive bash shell in a container
> docker exec -it <containerName> /bin/bash
# Run a shell command in a container
> docker exec -it <containerName> /bin/bash -c <shellCommand>

> docker build

Build an image from a Dockerfile

> docker build [OPTIONS] PATH | URL | -

Options

Option Description
-f <pathToDockerfile> Specify a Dockerfile that should be used, otherwise Dockerfile will be used.
--target <buildStage> Specify a build stage from the Dockerfile that should be build.
-t [<registryHostname>:<port>/][<repository>/]<imageName>[:<tag>] Tag image. registryHostName is only used when using a diffrent registry than the public DockerHub registry.
--no-cache Do not use the build cache when building the image.

Examples

# Build an image from a Dockerfile in the current directory
> docker build -t <imageName> .

> docker volume

> docker volume [COMMANDS]

Commands

Command Description
create <volumeName> Create a new named volume stored under /var/lib/docker/volumes
ls List volumes
rm <volumeName> Remove volume

> docker network

> docker network [COMMANDS]

Commands

Command Description
connect <networkName> <containerName> Connect container to a network
disconnect <networkName> <containerName> Disconnect container from a network
ls List networks
rm <networkName> Remove network

> docker network create

> docker network create [OPTIONS] NETWORK

Options

Option Description
-d <driver> Create a new network.
driverDescription
bridge(default)Allows communication between docker containers on the same host.
overlayAllows communication between docker containers on diffrent hosts(nodes).
--opt encrypted Encrypts network traffic
--subnet <ipAddresInCDIRFormat> Specify a subnet in CIDR format
--attachable Allows to connect not-swarm-containers to overlay networks

Examples

# Create bridge(default) network
> docker network create -d bridge bridge-network

> docker compose

> docker compose [OPTIONS]

Options

Option Description
version Get information about the docker compose version
ls [-a] List running compose projects. -a lists all compose projects.
-f <pathToDockerComposeFile> Specify a docker compose file that should be used, otherwise compose.yml or docker-compose.yml will be used.
-p <projectName> Specify an explicit project name that will get prepended to all not explict named docker objects, otherwise the directory name will be used.
-d Run in background
--profile <profileName> Specify the active profile for the compose file to adress certain services.
ps [-a] List running containers in the project. -a lists all containers in the project.
start [<serviceName>] Start existing services
stop [<serviceName>] Stop services
restart [<serviceName>] Restart services
pause [<serviceName>] Pause services
unpause [<serviceName>] Unpause services
run [OPTIONS] <serviceName> [COMMAND] [ARGS...] Run a service with its dependent services. The given options, which are similar to those for the docker run command, override those specified in the compose file.
rm [<serviceName>] [--stop] [--volumes] Removes stopped service containers. --stop stops running services before removing them. --volumes removes anonymous volumes attached to containers.
kill [<serviceName>] Force to stop services
images [<serviceName>] List images used by services
top [<serviceName>] List running processes of services
logs [<serviceName>] Show logs for running services
events Show all service events until stopped with keyboard interrupt
config Lint compose file

> docker compose up

Create services and start them

If no network is specified in the compose file, a default bridge network is created to which each service is connected to allow communication between services.

> docker compose up [OPTIONS] [SERVICE...]

Options

Option Description
--build Force image build before starting containers
--pull <option> Pull image before running:
optionDescription
policy(default)Pull image based on the pull_policy defined for the service in the compose file.
Default pull_policy missing only pulls missing images.
alwaysAlways pull images even if they exist.
neverNever pull images even if they are required.
--no-deps Do not start dependend services
--scale <serviceName>=<numberOfInstances> Create a certain number of instances of a service. Make sure that enough ports are published for port mapping.

Examples

# Create the specified services in the compose file
# and start them in the background under the given project name
> docker compose -p <projectName> -f <composeFile> up -d

> docker compose build

Build or rebuild images services

> docker compose build [OPTIONS] [SERVICE...]

Options

Option Description
--no-cache Do not use the build cache when building the image

> docker compose create

Create services

> docker compose create [OPTIONS] [SERVICE...]

Options

Option Description
--build Force image build before starting containers
--pull <option> Pull image before running:
optionDescription
policy(default)Pull image based on the pull_policy defined for the service in the compose file.
Default pull_policy missing only pulls missing images.
alwaysAlways pull images even if they exist.
neverNever pull images even if they are required.

> docker compose down

Stop services and remove containers and networks

> docker compose down [OPTIONS]

Options

Option Description
--rmi [local] Remove images used by services. local only removes images that don't have a custom tag.
--volumes Remove named volumes declared in the volumes section of the Compose file and anonymous volumes attached to containers.

Examples

# Stops and removes the services and networks specified in the compose file
# that are runnig under the given project name
> docker compose -p <projectName> -f <composeFile> down

> docker swarm

> docker swarm [OPTIONS]

> docker swarm init

Initialize a swarm

> docker swarm init [OPTIONS]

Options

Option Description
--availability <option>
optionDescription
active(default)Scheduler can assign tasks to the node.
pauseScheduler doesn’t assign new tasks to the node, but existing tasks remain running
drainScheduler doesn’t assign new tasks to the node. The scheduler shuts down any existing tasks and schedules them on an available node.
–-advertise-addr <ip|interface>[:<port>] Specify which ip/interface and port should be used for the docker swarm communcation.

> docker swarm leave

Remove node from the swarm

> docker swarm leave [OPTIONS]

Options

Option Description
-f Allows to remove a manager node from the swarm. Only use when swarm cluster is no longer used, otherwise demote it and than remove it.

> docker swarm join-token

Manage join tokens

> docker swarm join-token [OPTIONS] (worker|manager)

Options

Option Description
--quiet Only display token

Examples

# Pipe token that allows to join a new manager node into an textfile
# that can be uploaded to the node via scp
> docker swarm join-token manager --quiet > token.txt

> docker swarm join

Add a new worker or manager node to a swarm cluster

> docker swarm join [OPTIONS] HOST:PORT

Options

Option Description
--token <joinToken> Specify the join token
--availability <option>
optionDescription
active(default)Scheduler can assign tasks to the node.
pauseScheduler doesn’t assign new tasks to the node, but existing tasks remain running
drainScheduler doesn’t assign new tasks to the node. The scheduler shuts down any existing tasks and schedules them on an available node.
–advertise-addr <ip|interface>:<port> Specify which ip/interface and port should be used for the docker swarm communcation.

> docker node

Manage nodes in the swarm cluster

> docker node [COMMANDS]

Must be executed on a manager node

Commands

Command Description
ls List all nodes in the cluster
ps <node> List tasks running on one or more nodes
promote <node> Promote one or more nodes to manager nodes in the swarm
demote <node> Demote one or more nodes from manager to worker nodes in the swarm
inspect <node> Get information on one or more nodes
rm <node> Remove a node from the cluster

> docker node update

Update a node

> docker node update [OPTIONS] NODE

Options

Option Description
--availability <option>
optionDescription
active(default)Scheduler can assign tasks to the node.
pauseScheduler doesn’t assign new tasks to the node, but existing tasks remain running
drainScheduler doesn’t assign new tasks to the node. The scheduler shuts down any existing tasks and schedules them on an available node.
--label-add <key>=<value> Add node label
--label-rm <key> Remode node label

> docker service

Manage Swarm services

> docker service [COMMANDS]

Must be executed on a manager node

Commands

Command Description
ls List running services in the swarm cluster
ps <service> List the tasks of one or more services
inspect <service> Get information on one or more services
rm <service> Remove one or more services from the cluster

> docker service create

Create a new service in the cluster

> docker service create [OPTIONS] IMAGE [COMMAND] [ARG...]

Options

Option Description
-p <nodePorts>:<taskPorts> Map task ports to the node ports
--name <serviceName> Set the name of the new service
--network <networkName> Connect service to a network
-e <key>=<value> Set environment variables for the service
--replicas <number> Set the number of tasks that should be created for the service
--mode <mode> Set the mode for the task placement:
modeDescription
replicated(default)Given number of tasks will be placed on nodes.
globalEach node will run one task.
--constraint <nodeAttribute> == | != <value> Specify constraints that decide on which node a task should run
--endpoint-mode vip(default) | dnssr Specify mode for service discovery

Examples

# Create a certain number of tasks of a service but only on nodes that fulfill the given constraint
> docker create service --name <serviceName> -p <nodePorts>:<taskPorts> --replicas <number> --constraint node.labels.<key>==<value> <imageName>

> docker service update

Update a service

> docker service update [OPTIONS] SERVICE

Options

Option Description
--replicas <number> Change the number of tasks for the service

> docker stack

Manage Swarm stacks

> docker stack [OPTIONS] COMMAND

Commands

Command Description
ls List stacks deployed in the swarm cluster
ps <stack> List the tasks in the stack
services <stack> List the services in the stack
rm <stack> Remove one or more stacks from the cluster

> docker stack deploy

Deploy a new stack or update an existing stack

> docker stack deploy [OPTIONS] STACK

Options

Option Description
-c <pathToDockerComposeFile> Specify a docker compose file that should be used

Examples

# Deploy the services specified in the docker-stack.yml file under the given stack name
> docker stack deploy -c docker-stack.yml <stackName>

compose files: compose vs. swarm

compose file command compose swarm
build ✔️ -
deploy - ✔️
configs - ✔️
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment