Docker

Installation

Uninstall existing packages that might conflict

for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do sudo apt-get remove $pkg; done

Install using the apt repository

# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update

Install the latest version

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Test installation

sudo docker run hello-world

Updating

docker compose pull
docker compose up --force-recreate --build -d
docker image prune -f

Zsh completions

Create the script and store it

mkdir -p ~/.docker/completions
docker completion zsh > ~/.docker/completions/_docker

Add the following to .zshrc

FPATH="$HOME/.docker/completions:$FPATH"
autoload -Uz compinit
compinit

Shell execution

This requires the container to have a shell installed. docker ps can get the id of the container.

docker exec -it <container> sh

Secrets

Secrets must be used on the manager in a docker swarm cluster

Create a new secret

printf "my super secret password" | docker secret create my_secret -

Shell history should be cleared so that the password is not visible there if reading from stdin. Alternatively, you can read the password from a file through the method below

docker secret create my_secret ./secret.json

Use a secret in compose

services:
   db:
     image: mysql:latest
     volumes:
       - db_data:/var/lib/mysql
     environment:
       MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD_FILE: /run/secrets/db_password
     secrets:
       - db_root_password
       - db_password

Pruning

Images not in container

docker image prune -a

Containers

Removes all stopped containers

docker container prune

Docker stack

Switch to another docker context

docker context use {context_name}

Deploy services from a compose file

docker stack deploy --compose-file docker-stack.yml {service_name}