Aller au contenu

Docker

De Banane Atomic

Liens

Généralités

Docker permet de créer des environnements isolés du reste du système.
Il ne permet pas de faire de virtualisation et donc de faire fonctionner d'autres OS.
Couplé avec un système de virtualisation (Hyper-V), il permet de créer des environnements isolés sur d'autres OS virtualisés (containers Linux sous un OS Windows).

  • une image représente le programme avant son installation (installer ou une archive zip)
  • un container représente le programme une fois installé
Les images dockers sont pour les systèmes 64 bits.

Container

Un container est une instance d'une image. Il est créé à partir d'une image mais ne modifie jamais celle-ci.

run

Lance une commande dans un nouveau container. Téléchargement de l'image si besoin et création du container.

docker run <Repository<:Tag>>
# --name <ContainerName>
# -it : open a shell on the container
# -d : detach, run container in background and print container ID
# -v <LocalPath>:<ContainerPath> : monter un dossier local dans le container (-v c:/local/folder:/media/docker/folder)
# --rm : Automatically remove the container when it exits
# -p 8080:80 : mapping du port 8080 du host vers le port 80 du container
# -w /path/to/dir/ : set working directory
# --add-host=host.docker.internal:host-gateway : allow the container to access the host DNS (ex: localhost)

# list files and folders at / in the specified image
docker run --rm <Image> ls -al /

# open a terminal in the specified image
docker run -it <Image> /bin/bash

start

# démarrer d'un container
docker start <ContainerName ou ContainerId>
# -ai : open a shell on the container

# arrêter un container
docker stop <ContainerName ou ContainerId>

autres

# lister les containers actifs
docker ps
# -a tous les containers
# lister tous les containers et leur tailles
docker ps -as --format "{{.Names}}    \t{{.Size}}\t\t{{.Image}}"

# info sur un container
docker inspect <ContainerName ou ContainerId>
# get the IPs of all the running containers
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

# renommer un container
docker rename <ContainerName> <NewContainerName>

# supprimer un container
docker rm <ContainerName ou ContainerId>
# supprimer tous les containers
docker rm $(docker ps -a -q)

# se connecter au container via un terminal bash
docker exec -ti <ContainerName> /bin/bash
# -t : tty, allocate a pseudo-TTY
# -i : interactive, keep STDIN open even if not attached
# -e LANG=C.UTF-8 , force the encoding to utf8
# Ctrl+P+Q pour sortir du terminal bash sans tuer le processus

# exécuter une commande dans un container
docker exec <ContainerName> touch /tmp/test
# -e VAR=1  définit une variable d'environnement
# -w /root  change le working directory

# copier un fichier dans un container
docker cp /path/local-file.txt <ContainerName>:/tmp/file.txt

# suivre le log d'un container en direct
docker logs -f <ContainerName>

# open a postgres shell
export $(grep -v '^#' .env | xargs) && docker exec -it <ContainerName> psql -U $POSTGRES_USER -d $POSTGRES_DB

# run a sql script
export $(grep -v '^#' .env | xargs) && docker exec -i <ContainerName> psql -U $POSTGRES_USER -d $POSTGRES_DB < script.sql

Images

# lister les images
docker images

# télécharger une image depuis Docker Store
docker pull <Repository<:Tag>>

# sauvegarder l'état du container dans une image
docker commit <ContainerId> <ImageName>

# supprimer une image
docker rmi <Repository:<Tag> ou ImageId>
# supprimer toutes les image
docker image rm $(docker images -a -q)

# renommer une image : créer un nouveau tag et supprimer l'ancien
docker tag [image_ID] [Nouveau_Tag]
docker rmi [Ancien_Tag]

# lister les dangling images (sans tag)
docker images -f dangling=true
# supprimer les dangling images
docker images purge
# supprimer les images non-utilisées
docker image prune -a

# rechercher une image sur docker store
docker search <image name>
Useful images
Name Description
ubuntu ubuntu:latest tag points to the "latest LTS" ubuntu:rolling tag points to the latest version
debian debian:latest tag points to the latest stable release
alpine only 5 MB in size!
nginx
microsoft/dotnet dotnet/sdk⁠:10.0 dotnet/aspnet:10.0⁠

build

# build an image using the Dockerfile file and passing . as context
docker buildx build -t [image-name] .

# build an image using the Dockerfile.other file and passing the data folder as context
docker buildx build -t [image-name] -f Dockerfile.other data

Dockerfile

Dockerfile
FROM python:3.10-slim  # select the base image

LABEL maintainer="me@mail.net"
LABEL description="Description"
LABEL version="2.0"

ENV DEBIAN_FRONTEND=noninteractive  # during package installation via apt-get, the installer automatically accepts default answers

# install packages
RUN apt-get update && apt-get upgrade -y && apt-get clean && rm -rf /var/lib/apt/lists/*
RUN apt-get update -y && apt-get install -y gcc && apt-get clean && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# copy the context folders and files into the working directory of the container /app
COPY [--chown=<user>:<group>] [--chmod=<perms>] . .

# create a non-root system user to run the application
RUN useradd -r -s /usr/sbin/nologin -N -g nogroup -c "Docker image user" app

# configure a container that will run as an executable with parameters
ENTRYPOINT [ "python", "batch.py" ]
CMD ["default-arg1", "default-arg2"]
# override default arguments: docker run [image] arg1 arg2

# Build arguments
# docker build --build-arg MY_ARG=value
ARG MY_ARG=default_value
# log
RUN echo "MY_ARG: $MY_ARG";
# set an environment variable from the argument, it will be available into the container
ENV MY_ENV_VAR=$MY_ARG

Multi-stage Dockerfile

Dockerfile
# build stage
FROM mcr.microsoft.com/dotnet/sdk:10.0 as build

WORKDIR /tmp/app

# copy the context folders and files into the working directory of the container /tmp/app
COPY  . .

RUN dotnet build

# final stage
FROM mcr.microsoft.com/dotnet/aspnet:10.0

ARG ASPNETCORE_ENVIRONMENT=Production
ENV ASPNETCORE_ENVIRONMENT=$ASPNETCORE_ENVIRONMENT

WORKDIR /app

# copy the folders and files from the build stage /tmp/app into the working directory of the container /app
COPY --from=build /tmp/app .

ENTRYPOINT [ "dotnet", "App.dll" ]

Volume

# lister les volumes
docker volume ls

# lister les containers et leurs volumes
docker ps -a --format '{{.Names}}' | xargs -I {} docker inspect {} --format '{{.Name}}: {{range .Mounts}}{{.Name}} {{end}}'

# supprimer tous les volumes
docker volume rm $(docker volume ls -q)

Log

docker logs -f container_name

Clean

# vérifier l'espace utilisé par catégorie
docker system df -v

# supprime le cache de build inutilisé
docker builder prune -a -f

# supprime les images inutilisées
docker image prune -a

Backup

# backup the database
# $MARIADB_ROOT_PASSWORD, $MARIADB_DATABASE areexpanded inside the container (they are Docker env vars, not shell vars)
docker exec $DB_CONTAINER bash -c 'mariadb-dump -u root -p$MARIADB_ROOT_PASSWORD --databases $MARIADB_DATABASE' | gzip > /tmp/db.sql.gz

# backup the data
docker exec $APP_CONTAINER tar czf - -C /var/www/html . > /tmp/data.tar.gz

Exemples

.NET SDK + ASP.NET

# ── Build stage ────────────────────────────────────────────────
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src

# copy the sln and csproj to restore, useful for the docker cache layer
# the NuGet packages are nor re-downloaded if the sln and csproj have not changed
COPY *.sln ./
COPY *.csproj ./
RUN dotnet restore

# copy the source and publish
COPY . .
RUN dotnet publish \
    -c Release \
    --no-restore \
    -r linux-arm64 \
    --self-contained false \
    -o /app/publish

# ── Runtime stage ───────────────────────────────────────────────
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
WORKDIR /app

COPY --from=build /app/publish .

USER app

ENV ASPNETCORE_ENVIRONMENT=Production

ENTRYPOINT ["dotnet", "MyApp.dll"]

PHP

# apache avec php
docker run -dit --name apache-php -p 8080:80 -v /host/path:/var/www/html php:7.2-apache
Dockerfile
FROM php:7.2-cli
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
CMD [ "php", "./your-script.php" ]

apache

docker run -dit --name apache -p 8080:80 -v /host/path:/usr/local/apache2/htdocs/ httpd

mariadb

docker-compose.yml
image: mariadb
restart: always
environment:
    MYSQL_ROOT_PASSWORD: ***
    # optional, create a database and a user with full rights on that db
    MYSQL_DATABASE: mydb
    MYSQL_USER: myuser
    MYSQL_PASSWORD: ***
    # bugfix
    MYSQL_INITDB_SKIP_TZINFO: 1

Restore sql dump file

Depuis un hôte Linux:

# restore sql dump file
docker exec -i [mariadb-comtainer] sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' < /path/host/dump.sql

Depuis un hôte Windows:

# copy the sql dump file from the host to the container
docker cp sql-dump.sql [mariadb-container]:/
# restore the sql dump
docker exec [mariadb-container] sh -c 'mysql -u root -p$MYSQL_ROOT_PASSWORD -D mydb -e ''source sql-dump.sql;'''

# autre solution, fonctionne mais peut créer des problème d'encoding
get-content C:\path\host\dump.sql | docker exec -i [mariadb-container] exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"

bugfix

mysql

docker-compose.yml
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
    MYSQL_ROOT_PASSWORD: ***
    # optional, create a database and a user with full rights on that db
    MYSQL_DATABASE: mydb
    MYSQL_USER: myuser
    MYSQL_PASSWORD: ***

borg

# créer un container à partir de l'image archlinux
# monter Documents dans /media/data
docker run -v c:/Users/<user>/Documents:/media/data --name borg -ti alpine

# depuis le container
# màj
apk update
apk upgrade
# màj puis installer borg
apk add borgbackup

# se connecter au container
docker exec -ti borg ash

Swarm mode

Faire fonctionner plusieurs engine en même temps (ex: plusieurs services qui communiquent entre eux).

Installation

# installer docker et docker-compose
pacman -S docker docker-compose

# ajouter l'utilisateur au group docker
sudo gpasswd -a $USER docker
# Anyone added to the docker group is root equivalent
# se reloguer ne semble pas suffire, il faut redémarrer

# démarrer le service
systemctl start docker
# vérifier que le service fonctionne
docker info

Change docker root location

/var/lib/docker → /media/data/docker

sudo rsync -aHAX /var/lib/docker/ /media/data/docker/
/etc/docker/daemon.json
{
    "data-root": "/media/data/docker"
}

Erreurs

Failed to bind host port 127.0.0.1:8083/tcp: address already in use

# check who is using a specific port
sudo ss -tlnp sport = :8083

# list the ports used by containers
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Ports}}"

Your Linux kernel version is not supported for running docker

Linux kernel version 3.8.x.x-x is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.

Windows

À l'installation, choisir entre conteneur Windows et Linux.
Au lancement Docker demande l'activation d'Hyper-V (ce qui n'est pas compatible avec VirtualBox) et de Containers features.
Activer Hyper-V à la main: Menu → Turn Windows features on or off → cocher Hyper-V

  • Historiquement Windows utilisait Hyper-V pour faire tourner une VM Linux dans laquelle était installée Docker.
  • Maintenant, Windows peut faire tourner nativement des conteneurs Linux sans VM.

Windows Containers on Windows 10

Monter un dossier host dans un container

  1. Clique-droit sur l'icône Docker → Settings → Shared Drives
docker run -v [Host_path]:[Container_path] [image]
docker run --mount source=[Host_path],target=[Container_path] [image]

Installation

choco install docker-desktop
# nécessite de se déloguer puis de se loguer à nouveau pour que les nouveaux droits utilisateur soient appliqués
docker-desktop inclut Docker Engine, Docker CLI client, Docker Compose, Docker Machine, et Kitematic.

GUI

Kitematic

Clique-droit sur l'icône docker → Kitematic

Si les flèches du clavier ne fonctionne pas c'est parce qu'EXEC à été lancé avec sh

Entrer la commande bash

Ou Options (engrenage en bas à gauche) → Exec command shell = bash

Portainer

Installation sur Windows avec container Linux

md C:\ProgramData\Portainer
docker run -d -p 9000:9000 --name portainer --restart always -v /var/run/docker.sock:/var/run/docker.sock -v C:\ProgramData\Portainer:/data portainer/portainer
Error response from daemon: driver failed programming external connectivity on endpoint nervous_meninsky (5b7b910bf03ed74ba38b7dc442b6cc6c159ad8bad75b482884de72cd5a555ad4): Error starting userland proxy: mkdir /port/tcp:0.0.0.0:9000:tcp:172.17.0.2:9000: input/output error.