You are on page 1of 240

"

Øl
r

Understanding Docker
in visual
way
a

Learn discover Docker in sketchnotes


&
includedtips
with tips some

Aurélie Vache
000
C
0000

Øl
all
.
Understanding Docker
in visual
way
a

Aurélie Vache
-at
thanks to

Laurent, my
husband, Alexandre, my son, andall

the caring people who believe in me


everyday I

Thank you so much!!!

Reviewers
->

Thanks to Gaelle Alas, Stephane Philippart


& Alexandre Touret

who took the time to review this book.

⑭angelog:

m:
Release Date : 31/01/2021

UpdatedDate : 31/01/9023

Release Version c0

Changelog Re (will drawing


Length 8 937pages

Docker 8 20.10.21

2
#000

my car, "Sushi",
Thanks to who

CC 7)

dida lot purr sketchnoting with me -

****
**

-ences
Creative Commons BY.NC.ND
http://creativecommons.org/licenses/by-nc-nd/3.0/ 3
itentst table of

Dockerize everything @

?
y

What is Docker Ö
?
L
Docker Engine components O
Imag
y
O
1

s
\

Dangling images @
8
4

Build
Oz
YMMTI

images
a

Push images Q

4
j
puel retrieve
images Oz
&
\

layers Oz
I

§7
a

It container Q
)
)
Restart policies Q
5
L

Exit status O I
so

Run a container O
3
e

Copy to / from a container @


4
Exec in a container @2
y

stop & restart a container Ø

4
\

Pause & unpause a container @6


I

volume @69
l

Event Ø

4
8
@.
x
D Search

a
O
is
Security L

Scan vulnerabilities Øg
i

SBOM @1
Content Trust
@4 }
Run a container with
privileged mode
O 9

L
Run root
as non user
@7
-
stats Ö
105
y

ö
Clean & purge

NemoryBBFdBDqY
constraintscpU Or
?
context

Onoro
Network

system Ö
1
L

nanifest O135

5
Debugging I troubleshooting O "3

g
\

O
Dockerignore "43

Docker file ? i

;3
FROm Gs
LABEL Gsz
ARG i
O

6o
ENV
Ö 164

69
Ö
ADD & COPY

RUN
C 73
.

CND 8
string us JsoN
syntax O 175

CND & ENTRYPOINT


Ó178

EXPOSe i
O

83
VOLUME
Ò 186

USER
igo
O
WORKDiR
O
194
e
ONBUILD
O 17

Özar
HEALTHCHECK
O
200

STOPSIGNAL 2
o4
SHELL o
6
Tips Hulti stages build O

1o
-
&
l

Compose O
21

Extensions O

2z
) ools O31
T
Dive Ó
231

Hub tool ¿32


O
Ò
233

I
"
L
i
l
TrivyYjI 235
O
O


In the same collection

7
Disclaimer

/
I'm just Cloud & lover
a
technologies
who loves helping people & sharing

" "" " " "" " " " " """ " ""

I love trying explaining complex


technical things in visual
way
a
,

sketch notes
" "

in a
way .

/Hopping,y

8
nnptinn

?Iinuttornarnriinitiany,
furnt
trmrdina

c
o
Well let remind

's
,
things that matter

& good practices o

0
VO
ddå
ë

1.
Acontainer will die

Äl
9
Lep When
you
want to run
apps
in container think abouto

,
scalabilit y ) Being resilient

s Ephemerality I keeping images size

as small as
possible
j stareless

e
Preferlanguage
:
-

Ü
.

I nemory footprint

s With a
fast startup
Y
IH&
DMOMMDMM
E.
s with clean shutdown support

static executable binaries


j

10
tin

!
000 What is

Cs
0

oo0
Docker

?
create containers
I container based apps
Open
-
-Source
i s
M
IT C
0
000
Docker
oo0
3
.
MX
Enable portability L
Platform for developping shipping
,
f running
ÄT apps
It
Ät

11
I package one

-time
Build
then un chenever want
you

.
ax

I
O
aws
:41119 ipg
1nZ1
M
ws
)
12
Lini
00 Docker Engine
CD
00

o0
componerts

Qxv $ docher ~. W LL

Î
D REs
API
+
î
Idockerd
!
manages

! 5" Onoro
T
QBtn
13
Docker
Docker listens
- dlaemon for API
requests
I creates I edits I deletes objects

s Can communicate with other daemons

-
plient
I
Primary to interact with Docker Engine
- way
s
dockerCLI to
ss send
requests Crun remove 000) API
,
Can communicate with more than one daemon

14
Lul
0
Inages
C
000

s
Images are identified by an ame & a
tag

tag
repository o

Ø
acakewithlage
Iragine images
libe
.
T
-
-
layer
D
-t
Saßfet
t

-
-
-

lager
V

t
t Ob 2 42
ac
lager DcKlbdF

s lager 4612027
f
lager 7013842

-
An
image consists of everything needed to run an

application : code binaries tools runtimes dependencies 000


,
,
,
,
Layers be
images
can reused by 15
Should
? ? o
L
to

layers
I

each
need

time I
download all

pull an
image

?
Ro
o

č
C åå
already svailade

'layers
locally wont be dowrlerdess
o
egain

M Câche

16
?

Q IX
How to

?
I list all available ( pulled created myself
images
or

)
$ docker images

j list all Alpine images


$ docker images alpine

) List all images with starting "'

busy"
a name with

I
finishing by libe
"
$ docker images —-filter=reference=‘busy*:*libc’

&
) list all unused
tagged images ( images )
dangling

$ docker images -f dangling=true

w
8l-filter
) Remove ubuntu latest image
:
$ docker rmi ubuntu:latest

) Remove ubuntulatest
image
Leven if a
running container exists
)
$ docker rmi ubuntu:latest —-force
17
Linwi
00 Dangling
C
000

images

s Dangling images are not tagged


I not used by container
any

-
IBJp
.
x
enone 4 nones
):
-

¤
l
18
-

<gesarealso
known as
"

< none > :< none )


"

images

:

Becmsetheir epositoytag.ae/ mpty.Theyarenotref rencedbyanyg



images à containers

19
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 1234a56b78e 2 days ago 90MB

hnsystendruns
canheses
ingre tale wore
place indiad spase

.
Yon

eraud.
20
How EX
?
to

?
I list only
dangling images
$ docker images -f dangling=true

) Remove all
dangling images
$ docker image prune

Withoutaccepting the proupt gourcan


also
,
lichldisplay ther

21
tin

!
0

d
C
000
Build
images

-) In order to run in container we need to


app
an a

,
build I
package it in an
image

B o¤

DE my o
tag

-image
s docker build command builds
images from a Dockerfile

& a context

L
ë
Aortext be asctolfilus ina
pitt
rinanopjan

o By default docker build command search a Dockerfile


,
at the root
of your path l case sensitive =)
22
$ IX ?
Howto

?
Build
) an
image
$ docker build .

) Build an
image
I it with
tagged my and hol
tag

-awesome-image
$ docker build -t my-awesome-image:1.0.1 .

I Build an
image according to a
specified Dockerfile
$ docker build -f build/DockerFile -t my-image:tag .

) Build an
image from a
Git repository
( branch helloworldIDockerfile file path
)
main
,
$ docker build https://github.com/scraly/gcp-cloud-run
-demo.git#main -f helloworld/Dockerfile

Pechtlocste
Oh lat git clon this
repusiturs
's
,
,
the rainbraned

othe
23
tin

!
00
C
0000
push
image

In order to
through Dockerflub
- access
images
ora
private registry you
need to
push them

,
r
pus
the

tregistry

O
^ tag
24
By
I
defanet Docker deevon rushes

,
at
5
layers of an
image once

.
Inn
Set it
through - -
nax -

-coneuent
upload
25
How Ix
?
to

?
I Tag an
image that will be hosted in a
registry :

$ docker tag my-img:my-tag my-registry/my-img:my-tag

I Push an
image to a
registry

:
$ docker push my-registry/my-img:my-tag

26
tin

!
00
Retrien pee

C
000

,
images

- Images are stored in a


Docker registry

contains several
s A registry can
images

I have several tags


an
image can

By default Docker pulls images from Dockerflub


,
Ro
?
oV
EIwant
ubants
latest inage og
to retrievel pree the

dz $ docker pull my-repo/ubuntu:latest


urur

name
tag

DoodOhbut I sre

mouthenticated to nyrepe
yorare

O
0000

27
-

a. Ô ?
henta in
your repository
it
IT $ docker login

iath
Perfect ,
you
are

registry

a. Ô ? latest image of Ubuntu ?

À
[b $ docker pull my-repo/ubuntu:latest

28
yproiatho
od
inaguaity
aepers

T
f layer salbfed
j layer
D
D

f
f
-
J
F
8
F
bzackl
F

layer feÇlbdZ

- layer 4
b12c7f
s

s layer FC
1384c
ubuntuolatest

29
How Ix
?
to

?
) Pull last ubuntu tagged image

$ docker pull ubuntu

iLftag is not
definet defaret tog
,
is litest

) Pull all tagged images from a


repository lname
$ docker pull —-all-tags ubuntu

) Pull an
image from a
private registry
$ docker pull myprivateregistry:8080/user/image-name:tag

I list images available locally


$ docker images

30
DLes
i
Insecure registry

By default private registries


,
are reached

through HTTPS
.
You define them cc
insecure
can
registries

"
as

.
~1- daemon Json .
docherI
{
"debug" : true,
"insecure-registries" : ["myregistry.com:5000"],
"experimental" : true
}

31
ë sinerpn
.
part llayer of cake

çîî
a

e
layersaifedimage
D layer 8

b2ac4z
layer Ac

4lbdt
image
my - ny
layer 4612
-tag
o
G
E
-
czf
C
c layer FC
1384z
32
i

-
s
layers can be reused
by images

lapuntubger "
lager 26 138

e8
layer lager
s

f
8 8

b2ac4z
b2ac4z
lager Ac
lager 4

4lbdt
lbdt33
B layer 4612 layer 6 44
3 clf

c2f
- layer 7213842 layer 7

C1384z
lo 1.0.1
my o
my 0
.o
-image
-image
"

"
layers are
read immutables
-only"I
~
Layers are
identified by a
sha
2s6
unique
hash
s
G
c bd b la 68 3 12
c
33
LDochesfile steps don creak
lagers

't
necussary
other aree

V
,
LJ
RUN
i

O ADD

VE COPY

Other are intermediate layers


.
layers
Intermediate are deleted during docker build

size
Intermediate layers have a ØB

34
II Cache

?
eldiod IIbudeuldan

E
Iwanl to bild
my
from Dockerfile
image a

Q
66

d k
O layer already exists D layers doesn exist

't
,
in local cache
let build it
's
pull
?
stored

ron
Lun
instruction desn the cacte
't
use

35
How Ix
?
to

?
) list all
layers for a
given image ( and their size

)
$ docker history my-image —-no-trunc

) Display layers digest for an


image
$ docker inspect -f '{{json .RootFS.Layers}}'
scraly/simpleapp | jq .

36
Lini
00
CB Registry
000

7registry is storage for images


A
a

A contain
s registry can several
images

have tags
.
several
image
I
an can

37
- You can run
your
own
registries or use
existing ones
s
lihe
Dochwtlub

dockerhub

iL By defaret Docker pullfrom


ivages
,
Doctetlub
egistry

38
?

How IY
to

?
I Pull an
image from a
registry
$ docker pull my-registry/my-image:my-tag

I Tag that will be hosted in


registry
an
image a

$ docker tag my-img:my-tag my-registry/my-img:my-tag

) Push an
image to a
registry
$ docker push my-registry/my-img:my-tag

39
.
o
C
olisr Fran

tated ina
rerere
theimag
uegictoon

û
$ docker image remove my-registry.com/my-image:my-tag

E
but this command
Sorry
,
celonsgue
rerring yourimage locally

O
{
( {
äd

40
auwtie
tatmnnmmngthen
o
L

čd
container layer
î

ÄTT layer
lager
Saßfet
ObZac
4z
lager Dc
4lbdt
r
lager 4612027
f
lager JC
1384z
41
s An application running in a container

can
only modify the container
layer

Writecontainer layer Red

-
î
base

}
layer Saßfet images
lager ObZac 42

lager Dc layers
4lbdt
lager 4612027 I Read I
f
Cager 7013842

-Only
s

Lconteat stored

nurring
in this contaiver layer loss
."
ther ontainer is he
fonger

42
s 2 docker run will create 2 distinct containers

bianis
ble
ra
Ol
acburor
de

my 8
tag
\,
Sdockerun
-image
de

bianistable OIl

43
?

" IX
How to

?
) Create a container with a
random name

$ docker container create my-image

I create a container

$ docker container create —-name my-container my-image

iL cocke ontriner weoke

shortal
owrand

socker weake
.
have a

I Rename a container

$ docker container rename my-container my-awesome-container

) list
running containers
$ docker container ls

list all the containers

$ docker container ls --all

44
Linwi
00 Container
CB
0000

Restort policies

- Several restart policies exist with --


restart

option that defines how a container should or not

be restarted on exito

tno
restart
- Default policy
s
container
Never restart
automatically a

45
talways
- Always restart a
container regardless
s
of the exit status

õ
Jqu

*
Docker restart
daemon
indefinitely

$ docker run —-restart=always my-container

46
toon

-failure
container it exits
-
Restart a
only if
s
clue to an error

+
Jqu ~ *
Docker restart
daemon
if fails

$ docker run —-restart=on-failure my-container

onson
Win
tinit the nouber ofeshart etrices

the Decka sterts


.
$ docker run —-restart=on-failure:5 my-container

47
tunless

-stopped
- Restart a container unless it was

stopped before the Docker aemond

was restarted

$ docker run —-restart=unless-stopped my-container

48
Y It?
Houto

?
restart container
y change policy for a
running

$ docker update —-restart=unless-stopped my-container

L Restart

a container
policy only takes
starl
,
effect after
successfully

¤I
I started successfully
I
for
I if up
'm
at least 10 seconds

) the number of restaits


Display
for my container
-container
$ docker inspect —f "{{ .RestartCount }}" my-container
49
Lin

!
00 Container
C
0000

Exit status

- Exit status code giveabout


information

why a container failed

Exit code follow the standare


chroot

50
?

QYIY Exit wodes

iss

cha
ê
$ docker run —-myflag busybox; echo $?

i
" cannotbeL containerd ommand
It
I
$ docker run busybox cmd; echo $?
-

r
i
L containerd command cannot be

$ docker run busybox /etc; echo $?


invoked

. -

51
I
iI
O 7
s
kot fatal ervorsignal

container
i0 terminated by CoNTRoLtC

containg
3
120 siakice
t1
.
receivedl a

128+1,
sigTERy
43

i
.
container received a

52
00 0000 tii Runa

C container

s A container is based on a static image

ss cocker command allows


you running
run

container from an
imagea

s cocker start command starts a container

& all its


previous changes

T
IYJdAmej
-
.
Oll

don specify iksname


't
Jou
ëI
,
Declo generales a randow twoe coradsnore

53
IT
Howoork dees it

!
ludul Iboleveday
1
E Does the

the local cache


image is in

?
çî blo
WT Cache

ì
@

intheregistry
If not it is then searched
,
ipueled il 2.

Nstored inthe local cach O store

Qv
blo
Docker I
@ registry LJYYi
BJ
iwe
.
Estart a new container
1-
poleh
o

Tusan
GV
blo

O 54
?

" Ix
How to

?
) create a container

$ docker create -it —-name busybox busybox

) Start a
stopped container

$ docker start my-container

) Run a container from debian


image

$ docker run debian:stable

{
Run O dochercreate
Ddocherstart

55
) Run container it execute

&
a name

,
echo " sketchnotes lovers command

"
hello
$ docker run busybox —-name busybox echo "hello sketchnotes lovers"

O
container will execute

thowenonad

then it oill oa terinatul

I Run container & interactive terminal into


it
open
a an

$ docker run -it busybox /bin/sh


wn

- 1.- i n t e r a c t i ve :
allows
you to interact
i
!
run commands in the container

t : attach remote console


1-tty
to our locale console

will this option wotainer oile


,
not be stopped
56
I Run a
temporary container

$ docker run —-rm -it my-img:my-tag /bin/bash


un

-- 8 container will be removed whenits exists

rm
) Run a
container with detached mode

&
exposes ports

$ docker run —d -P —-name my-container my-image


un

- true : detached mode


d/-d=
-
publish all exposed ports
P8
M

E
Dctached vode a local turminal

to the
is not attacked
runing antainer

¤
î
57
Run container & specify custom
porks
) a

$ docker run —p 8080:80 my-image:my-tag


an

- map
local port to remote port

p:
O
*

BT
Oëbos
.
n

0
mr

http://localhost:8080

Ei
Gool M I can
.
access application locally
L throughe hHpill locathist 6080
o
:
çd
) Run a container & write the container ID in a
file
$ docker run —-cidfile /tmp/cid.txt ubuntu echo "hi!"

58
) Run container & environment variables
a
pass

into it

$ docker run -it —-rm -p 5432:5432 \


-e POSTGRES_USER=my-user \
-e POSTGRES_PASSWORD=my-password \
postgres:9.6.10-alpine

ef set or override environment


--envo
variables

59
tinl

!
00 Copy tilfron
C
000

a container

Docker allows
files & folders
s
you copying

from machine to container


your
a

from container to local machine


your
a

cp
myfile container
cher
F
M ij :
*

x
yJ
*
O
O -

Äl
-

I O

ë
-
@
myfile
docher ep containerixx
$
s

L
Frisnol possible to
copp specilis aphengile
tuch as resoucses under ( ly
"
pros,
llenstinl

60
?

How IX
to

?
"

file from
"

container to
) Copy report xme a
my
.
local machine

$ docker cp my-container:afolder/report.xml .

Copy conf file container


"

) init inside
"
a
.
$ docker cp init.conf my-container:conf/env/init.conf

61
Li

!
000
C
000
Execina container

s docker exec command allows


you running
commands in a
container

w Useful to debug in
your
container

$ docker exec - container bash


it
-
o
-

Äl
i $ ls -l
$ cat path/to/a/file

62
?

How IX
to

?
I Connect to a container & open an
interactive shell

$ docker exec -it my-container bash

Wit I ty
-- 8 interactive shell

--interactive
> ls -l
> tail -f /var/log/debug.log

) Execute a command in a container in


background
$ docker exec -d my-container touch path/my/file

Wd o detached mode
/-detach
63
tilistopf
00
Ristart a
C
0000

container

stopI

s
docker stop command stops any running containers

$ docker stop my-container

ÄŞt xx

loceaede
sychignet I send sistEien signad

\
wait
)
signal
send sigkill

Jq
Restart
- clocker restart command restarts
any running containers
s
iI You on stop
o I
and

ontainer
restir t
specifies hamorontier
64
1s
?
8
Yà IY
How to

?
Y stop container my

-container
$ docker stop my-container

I stop container
my which have

-container
estart =
yes configuration
$ docker update —-restart=no my-container
$ docker stop my-container

Y Restart container
my
-container
$ docker restart my-container

) Restart container
my
container but wait 15 seconds
-
before hilling it

$ docker restart -t 15 my-container


in

t
1.-time
65
ti

!
00 Pause O npause
C
0

oo0
0 O
acontaine e

Tause
docker pause command
pause
s all
of the

inside one or several containers


processes

$ docker pause my-container

Ät
Sun Nov 27 12:09:40 UTC 2022
Sun Nov 27 12:09:42 UTC 2022

¤
i
E isend siastop signal

âq

66
unpause
- docher command all the
unpause unpauseprocessess
s
$ docker unpause my-container

Át
Sun Nov 27 12:09:40 UTC 2022
Sun Nov 27 12:09:42 UTC 2022
Sun Nov 27 14:01:12 UTC 2022
Sun Nov 27 14:01:14 UTC 2022

Å ¤
%
67
IX

Q
?
to
tow

?
) Run a container that
display the date

2 seconds
every

$ docker run --name my-container alpine /bin/sh


-c "while true; do sleep 2; date; done"

And run another container

$ docker run --name my-container2 alpine /bin/sh


-c "while true; do sleep 5; date; done"

I Pause container my I 2
-container
my
-container
$ docker pause my-container my-container2

I Unpause container my
-container
$ docker unpause my-container

68
W
O

000
o
C
000
Volumes

s volumes enable persisting data

You can nount local folder inside a container


-

using a volume

s
They can be shared among several containers

Äl Äl ÄT
11
Y
Øl
w

my
-volume
Volume don increase the size of container
't
a
o

ë
s
l Container
lifecycle I

Volume 69
iL
volunes cresound in the rost

/var/lib/docker/volumes/
gilnsyster

70
?

How IX
to

?
volume
Create a
?
$ docker volume create my-volume

List all
volumesy
$ docker volume ls

) Run a container & create a volume

$ docker run -it -v /etc:/my-etc my-container bin/bash


wmm

host dir folder inside container

o
o Create a
volume

L O
Nount local directory
inside container

âq
a

71
) Run a container with a
volume named
my
vol

.
$ docker run -it -v /data —-name my-vol my-container /bin/bash

contaner
Attach running container
a volume to another

$ docker run -it —-volumes-from my-vol my-container2 /bin/bash

I Run a
nginx container
I mount a volume with read access

-only
$ docker run -d -v nginx-vol:/usr/share/nginx/html:ro
—-name nginx-vol nginx:latest

D And whatabol
wolam cleaning
?
,
¤
î
Øl
volume
unamed
B
mune
w
9
?
volume
wnamed
my
?
-e
QI
volume
wnamed
?
Y Delete a volume named my
vol
.
$ docker volume rm my-volume
72
create two volumes
) Run a contai ner ,

en
remove them when
d ed
top command has

$ docker run —-rm -v /my-folder -v my-vol:folder busybox top

Ä
d X
øX
sunamed volumes my

-vol
Y Remove all volumes
$ docker volume prune

73
Lin
00
Cn Erents
00

o0
ÄT
?
Real events from the server
-time
ô
D
= ono
s
0n
1000 logevents
.
default last
B y are
displayed
,
s
It possible to display events since :
's
s k mo
date
timestamp relative time

74
?

How IY
to

?
Y Display events since 5 minutes

$ docker events —-since ‘5m’

related
y Run container &
display in real

-time
container events
's
$ docker run img & docker events
—-filter 'container=$(docker ps -lq)'
w

olast
quiet
0
I Display events in JSON

$ docker events —-format ‘{{ json . }}’

) Display A events
pine image
's
$ docker events —-filter ‘image=alpine’

75
events
) Display stop on a
test container

âîp
Ál C
~

y
-container
w
~
~

n
mm

$ docker events —-filter ‘container=‘my-container’


—-filter ‘event=stop’

76
Lini
000
searn
C
000

When want to
find image in
"
you
an
s
a
registry firs hab it is to search in VI

000
,
{ta


C
~

dockerhub

4
o

PÖ0
U

ooo

But do you know you


can search
directly
,
through Docker CLI
?
clocker
is By default search command search
,
Docker Hub 77
in
?

"
D
Ix
How to

?
y list Ubuntu image

$ docker search ubuntu

) search in
private registry
a
my image

-image
$ docker search <registry_host>:<registry_port>/my-image

I list Debian image that have more than 10 stars

$ docker search —-filter stars=10 debian

) list
official Alpine image with up to sresults

$ docker search -f is-official=true --limit=5 alpine

I list busybox images without

any
truncated description
$ docker search --no-trunc busybox

I list ngint images & format the


response

$ docker search
--format "{{.Name}}\t{{.StarCount}}\t{{.IsOfficial}}" nginx

78
Liunw
00
C seen
0000

Scan vulnerabilities in local images


ws
your
Dockerfile
&
Bul
,
fecture
ved
v e to install
rs Docher
i in
on Edlge

distrlL
Don work for Alpine
't
79
?

How IY
to

?
Y Scan a
local image

$ docker scan my-image:my-tag

I Scan
image with a detailed analysis
$ docker scan my-image:my-tag --file Dockerfile

I Display the dependencies


$ docker scan my-image:my-tag --dependency-tree

J Display only vulnerabilities in


your
code

L excluding base
image 1

$ docker scan my-image:my-tag --file Dockerfile


--exclude-base

) vulnerabilities
Display only with high severity
$ docker scan my-image:my-tag --file Dockerfile
--json |
jq '[.vulnerabilities[] | select(.severity=="high")]'

lorests
perverth
are T o inverse this puota
alloced
.
,
youned to sigrup for ge sugh acoerd
.
80
Q LiBor
00
C
000
aperimentad

de

sbor

lloftrare
-

naterial
Bie
of

.
An inventory
componente
e
of ale the
I all the software dependencies
in a container image

EckasÇüuamÜ
BdAjix Lpndnen
I
¤
izuÜtüWü
s
}
81
?
Why
z
s To find packages
that can contain vulnerabilities

Forexampleë
ces
.
EFwant my
to search if

image contains
loge ?
Ro
O
(6
Q
Yisthurfst
locker sbor yucan
"
c
çp
åd

iL daker service stom syft insing


,
hur it
way change in the Guture
82
Q Ex?
How to

?
I Generate a SBOM
for an
image

$ docker sbom my-image:tag

I Generate a SBOM in an
output file
$ docker sbom ubuntu --output sbom.txt

Y Generate a SBoM in IsoN


format
$ docker sbom ubuntu --format syft-json

83
Lini
00 Conteal

C
0000

trust

u Most of Docker images are


unsafe

,
the Docker Hub
even ones
you
can
find in

ncrease the trust in


imagesI

thanks
c docker trust
to o nn

-
A tagged image can have a
signature

.
It attests
you
created & published the tag

.
T
my tag
I
-image:
ë

En official inages are


signed
84
enable Docker Content &
ws
You can Trust

protect y
our host for unsigned images

$ export DOCKER_CONTENT_TRUST=1

QîC
Iwal to pull
anirage

..
$ docker pull scraly/what-is-my-pod:1.0.1

C
Cortent Trad is erableds

pourcanit preeancign
images V
Wx
o Ütt
čž $ docker pull busybox:latest

Esa signed image


V
V
l
Øk
85
Orce
Gateal Truct is enabled

,
docko pushorwand will pus
inagedl
ą
nsign the

,
" Every time you sign a
tagged image
s
or revoke a
signature
,
must enter
you
a
passphrase

86
?

Q IX
How to

?
T rush
Enable Docker ContentY

$ export DOCKER_CONTENT_TRUST=1

TDisable
rushI Docker Content

$ unset DOCKER_CONTENT_TRUST

tag
Creake new a

$ docker tag scraly/what-is-my-pod:1.0.1


scraly/what-is-my-pod-signed:1.0.1

image
Push & sign the

$ docker push scraly/what-is-my-pod-signed:1.0.1

S Display information about key & signature


in JSON format
$ docker trust inspect scraly/what-is-my-pod-signed:1.0.1

I Display information about key & signature


in readable
a more
way
$ docker trust inspect scraly/what-is-my-pod-signed:1.0.1
--pretty
87
) Sign the 1.0.2 tag
$ docker trust sign scraly/what-is-my-pod-signed:1.0.2

I belete signature for 1

o2tag
$ docker trust revoke scraly/what-is-my-pod-signed:1.0.2

key
Generate signing a
-pair
$ docker trust key generate my-key --dir my-folder

encrypted
ceate

f \ v
load
the

private key


my 1 my key pub local
-folder
docker
-
.
trust
keystore

88
tini
Runwith
000
CD privileged
0

oo0
node

C
By defanet containers are umprivilege
,
To

1
89
-
privileg
-
Grantcapabilitie
to container root
a

to all devices on the host

Thanks to this mode


~ you
can
s
run Docker daemon in a container

E
with
privileged mode

,
containe hove super povers

0
+
[*
13) Do
d
1ld
90
It
not recomiended
containers privileged
to ror

w
production environment

.
in

.
Be careful this
usage

.
)
91
?

How IY
to

?
) Run a container with privileged mode so it can

access to all devices in the host

$ docker run --privileged my_image:tag

I Run a
container then create & mount a
,
temporary file system
$ docker run -it --privileged ubuntu mount -t tmpfs none /mnt

I check if a container is in
privileged mode

$ docker inspect
--format '{{.HostConfig.Privileged}}' my-container
wv

c ~,
true false

92
OI
S devices

.
Allows to reduce rishs with privileged mode

iW
the rightr
defalt ortaivers cor read

,
write d ubnoed
,
Kerices bud can custorize
pou

93
?

How Ix
to

?
I Run a container which can
only
read partition table

$ docker run --device /dev/sda:/dev/xvdc:r --rm -it ubuntu


read

I Run a container which can


only
read I write partition table

$ docker run --device /dev/sda:/dev/xvdc:rw --rm -it ubuntu


co

read &
write

I Run a container which can


only
allow nknod permission

$ docker run --device /dev/sda:/dev/xvdc:m --rm -it ubuntu


in

mknod

94
IIapradd
s
scap I
-drop
s Allows adding
f drop Linux capabilities

95
ąi E
!?
Hoo to

?
j Run a container which use all capabilities
except for chown

$ docker run --cap-add ALL --cap-drop CHOWN ubuntu

I Run a container which mount

a FUSE based filesystem

$ docker run --rm -it --cap-add SYS_ADMIN


--device /dev/fuse sshf

96
Lin

!
00 Runas nen

-rod
C
00

o0
user

- By default Docker runs containers as root user

,
,
with root privileges

proble

Oi O
O ¤
"
( ëo 7

j Running as
root can cause
security issues

Anyone start undesirable


can
processes

in the container

I Malicious user can


change the UID & GID

when starting the container


97
practic
Best

V Give the minimum amount of privileges


to
necessary run a
process

o Run containers as non root user

98
?

Q Ix
How to

?
I Run a container & check the container

is root
running as

$ docker run --rm busybox id

unable to find image busybox latest locally


00
o
Status Downloaded newer image for busyboxilatest
:
wid root gid groups
= (

lo
:O(
wheel)
:0Crook)
)
) Run a container & force the container

to start with a
given VIDI GID

$ docker run --rm --user 1000:1000 busybox id

aid 1000
gid 1000
=
:
99
I create with UID
"

666,

myuser"
a user

give the rights to lapp folder & use it

FROM ubuntu:latest
RUN useradd −u 666 myuser
WORKDIR /app
COPY . /app
RUN chown -R myuser /app
USER myuser
CMD ls -alrt /app

100
-

User
-
Namespaces

linux kernel
- A
concept of
s
Is solated namespace

simulating a root
namespace

lédéâöö
namespace

I
ral inside this
i
usn
hanesras

isnapdudto a
nou vis
-privileged
L uthe Decbenbat

¤
101
icontainers
ncan root have privileges
the user names pace without

having Docker Host


any privileges in the

102
?
8
di IZY
How to

?
I Enable userns remap on the Daemon &

-
start the default user
namespace with
to
the dockernap user & group mapped
non UID and GID
-privileged
~1- daemon
.json
docher)
{
"userns-remap" : "default"
}

Or

$ dockerd --userns-remap=default &

O
2
Verif Docker have created

the dockermap userforyor


$ id dockermap

103
containe
Now
you
can run a

.
isolated for the host

$ docker run -it -v /bin:/host/bin busybox /bin/sh

IInauser
nanespace yor

can
have an impact
to
't
L the host

õd

104
tu
Cn isar
000
000

Display containers streamed


- unning sage information

EFhare
inferaliodagu
?çîî
Ro
o

Q 2' CPU%

}
s
firrornire nemory usage
:
OF
linit
nemory
nemory %

Network ilo

Block Devices Ilo

L It stats aboud stoppes


possiblet gory
's
ontainus but information will be
enpty
.
105
?

How IY
to

?
I Display information for all containers
running

$ docker stats

) & container 2
Display information for my

-container
$ docker stats my-container <container_2_ID>

I Display non streamed stats for my

-container
$ docker stats my-container --no-stream

I Displ y
stats
in ap o n s e
re s
customized for mat

for all containers

$ docker stats -a
--format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"

I Display stats for busybox in JsoN format


$ docker stats busybox --no-stream --format "{{ json . }}"

106
tiiclean
o

0
C &
000
rurge

{ }
pull
-
Each time
you images & run containers
build

,
s
data are stored in machine
your

.
Novel
build
G

z
run x

fd
107
- stored data can be

:
s
tw
containers images volumes networks

xu
Oworo
VT

1
througho
All theses data be removed can

EX
-TERMI-NAT
mnøtooë L

when a contaiver ic
rewored a
velere
,
not atonaticaly renoved
.
108
IX

Y ?
to
How

?
XT

sumra
) Remove a
container

$ docker container rm <containerID>

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

) Remove all
stopped containers

$ docker container prune

109
i
$ docker rmi <imageID1> <imageID2>

$ docker images purge

} Remove all
images

$ docker rmi $(docker images -a -q)

110
Q

Grma
Remove a volume

$ docker volume rm <volumeID>

$ docker rm -v <containerID>

my
-container
E Andowo

purge
My farurite
command

Y Remove
images containers volumes
,
,
,
networks active t stopped

$ docker system prune -a --volumes

111
% !%¥ constraints
%☒☒_☒¥☒&
• a

>

.in#fi-a-ins
,

→ By default Docker ,
containers don't have memory limitations

→ Containers can use all available memory they want

on the host

When define container can swap



you memory ,

the same amount

__memory12 "
☐I

}
128m for memory IN REALITY

128m for SWAP 256 m


M.

Becafefue.us#-QcJanslowdownperformances.J
-

to the disk
Indeed , system will write .

112
2.

It |HowT◦?
Run container & set the memory usage to
60 mb
> a max

$ docker run —-memory 60m my-image:tag

> Run a container & use unlimited amount of SWAP

$ docker run -m 128m --memory-swap -1 my-image:tag

'

p-nemhgsam.TT
- m


> Run a container & deactivate 00M Killer

$ docker run -m 128m --oom-kill-disable my-image:tag

yaho .li#equaestothesystemani.eabe memo.ythatyouG


limits the memory inside the containers
-

memory usage ooo


-

can see with free command inside a container .

113
-

What is a 00M Killer ?


<
0
*
Fb

ooe=ⁿÑ%
→ Wakes up when there is no
enough memory

on the system

Kills the until the


→ greediest processes system
recovers
enough resources to keep them running

feature

1 \GB
~ ☒ñ: É
memory

114
?
%
It

> Set a max


memory
& limit to limit to 60 mb
a SWAP
really

$ docker run —-memory 60m —-memory-swap 60m my-image:tag

-
numbers are
equals →→ container will not SWAP

115
?⃝
don't have CPU limitation

By default ,
containers

It'snotpossibÉahi§f
the available number of CPUs on the host

116
?⃝
%iiH◦wt
> Run a container & limit its CPU utilization

to 1 CPU

$ docker run —-cpus 1 my-image:tag

> Run a container & set it can use


only
50% available
of CPU

$ docker run —-cpus .5 my-image:tag

117
?⃝
Dei
→ Allows to separate containers onto
you
different CPUs or cores

- -

cpuset .

cpus
1
,
2
,
4

6 & ~
::
' ' I
-

I .
-
:
÷ ÷.

⑥ ① ② ③ ④

i:

00
- -
cpuset -

Cpus means :

• • a list 1,2, 4

0-3
• a
range

startingfromOB.LI
basic index
Be careful ,
- -

cpuset -
-

cpus use

118
→ Defining an invalid CPU index will throw an error

119
ÑiH◦w
> Run a container & allocate the 2nd
and 3rd CPU

$ docker run —-cpuset-cpus 1,2 my-image:tag

120
Li

!
00
Context
Cn
0000

7 Allows to handle the connection o

remote Docker instances


Inodes

121
O
sdockernoO O cLz

Öf context

ååÜğ
I
D REST
API

î
dockerd $

djages\ s
,
O

QB
J zoro
V y

u
122
iI
bpefmet a
default ortixt iccreated

,
Docher local
requolet your
installation

123
?
o
Yù IY
How to

?
) List existing contexts

$ docker context ls

I create a new context to our another Docker host

$ docker context create dev


—-description "Development environment
—-docker "host=ssh://$IP"

) Switch to our der context

$ docker context use dev

Now you can list existing containers running


,
in the second host

$ docker container ls

I Run a new container in our


default context

$ docker —-context default run -d -p 80:80 nginx

context
Save
your
?
$ docker context export dev

124
tn

!
00
Network
C
00

o0
-
Containers in a same network can communicate to

each others

Ö my
-network
my my 2
-container
-container
isolation
A form of

the default
-
By default a container is attached to
,
bridge network

7 3 networks are
automatically created by default
t m
.
bridge host none

125
bridge
driver
Default network

- Allows containers connected to the same bridge network to

communicate to eac h others

h Isolate other containers not connected to that bridge networ


.
ëXnd can
jou per bridge networed
create
your
owr
.
-defined
¤
Äl IIT

I
my uy s
-coutainer
-container}
Ď= Ď
*
*
my
-network
ÄT
my my 2
-container
-container
Ä my
6
-container
my4 126
-container
host
containers
for standalone

s Remove nerwork isolation berween the container

& Docker Host

s Used host networking directly


's
none
Disable all networhing for
containe a
.
C Eingullzisecked

I
+
my
-alone-container
127
overlay
connect muetiple Docker daemons
together

~) Used to facilitate communication between a swarm service

I a standalone container

maculan
containe Assign a MAC address to
a
.
device
Naking it appear as
a physical

s
Docker daemons routes
traffic to containers by their

MAC addresses

I third networf plagins can


aes
.
-party
be justalled

128
?

ù IX
How to

?
y list existing networks
$ docker network ls

I Run a container that need to be isolated

$ docker run —-network=none ubuntu

network
Connect container to existing
a an

$ docker network connect my-network nginx

user
Disconnect container from a a
-defined
bridge network
$ docker network disconnect my-network nginx

129
E
ters troubleshoh
? retvorkissues
?
Ro
ov

ç
O
Without changing an
existing
ining crtainer ce canruna

,
i new container to debugI troubleshoot
it v o
H
6

l
O launch a container ( that has potentially an issue

)
$ docker run -d —name my-broken-container nginx

Q Run another container that share the same network

$ docker run -it —-network container:my-broken-container alpine


m
create that be
we a
namespace can

shared for troubleshooting troubles

Then inside it install tools for debugging o


,
,
$ apk add —-update-cache iproute2 bind-tools net-tools

And finally debug


$ nslookup localhost
$ netstat -laptn
130
Liuni
00
Cs system
0000

1
Useful commands to
query

Docker internally

E Ash re

eralmost
anything
n
on
^
ooč
C
0000
o

131
The of socbe syst
hef

comande have sho coll

¤
C1
chwsterewnté
l
-
ô

Real
-

docker events

time events
server
Ozoro
wos
-

from
s
sú nc

l
clieat do cker sstem ingo

l
y
kernee -

experimental
-

Debug
mode dockenin Server
cpus
8o
-
Display sytem information
-wide
132
?

How Ix
to

?
I Display all
sytem wide information

-
$ docker system info

I Display Kernel version system information only


$ docker system info -f '{{ .KernelVersion }}'

Docker diskusage
I Display
$ docker system df

Docker disk
detailed
I Display usage
.
$ docker system df -v

) Display Docker disk


usage
in JSON

$ docker system df --format '{{ json . }}'

133
I eal
Display events

-time
in

$ docker system events

containe
Display events for my

-container
.
since 15 minutes

$ docker system events


--filter 'container=my-container' --since '15min'

oCAudlone
ofmy
Savorite connand an

țŽ
j Delete all unused
images containers
,
,
networks volumes dangling images
,
,
& build cache

$ docker system prune -a --volumes

134
aperinentd tunl
000
C
0

oo0
nanifest

de

s Information about an
image layers

:
?
size

I digest I hash

v
TBJide~ L
L
u ,
,
architecture

OS

Each
- manifest entry represents
s
a
different variant
of the image

( AHD ARM
64000)
64,
x86,
Drcher uses
manifests to know if an
image

WI the curcatderice
is
conpatibl with
.
1 hor to stat aremantaine
.
135
?

How IX
to

?
I Display the manifest for busybox image

$ docker manifest inspect busybox

I Display the manifest for busybox image

the image tag , fos


's
architecture
$ docker manifest inspect busybox -v

Y Display the manifest for an


image

from an insecure
registry

$ docker manifest inspect --insecure 127.0.0.1/my-image:tag

136
images
Create multi

-architecture
( ARM 64)
AND64&
# AMD64 Architecture
$ docker build -t my-image:amd64 .
$ docker push my-image:amd64

# ARM architecture
$ docker build -t my-image:arm64 .
$ docker push my-image:arm64

# Combine the manifests


$ docker manifest create my-image:my-tag
--amend my-image:amd64
--amend my-image:arm64

# Push the manifest


$ docker manifest push my-image:my-tag

Thanks
to this narifests
AaDce inage faM users

can reats containers grou


this

ãî
Or
$ docker buildx build
--platform darwin/amd64,darwin/arm64
--tag my-image:my-tag
137
I Annotate an
image

$ docker manifest annotate my-image:my-tag my-image:amd64


--os-version darwin --arch amd64

I Delete the manifest for my

-image
$ docker manifest rm my-image:my-tag

138
Linw
i
00 Dekuaging
CD
000

trobleshooting

o When an error occurs keepcalm


c

,
>5
& analyze step by step :=

containers
s
Display all containers

( stopped l inactive fterminated


even
)
$ docker container ls -a

show logs
containe
- Don hesitateto watch container logs in order to
't
s
'
try to understand what is
happening

{t

pDÜ
C

Äl
~

o
$ docker logs my-container
stdoot
n
x

~
me

r
~ U
un

139
Cool but I want to stream the logs in realtime 8
,
$ docker logs -f my-container

-8 t--follow.
stream logs from STDOUTI STDERR

Execin
contain a

s
Debug in container & execute commands directly
your
intoiro

$ docker exec -it ubuntu bash

Yir I interactive --
try o interactive shell
--
i
E You car watch

logs
specific

Q $ tail -f /var/log/access_log
6
b
140
O published ports exposed by
containerwe a

ones
My container expose port oobet
which

?
?. ?
?

Øå $ docker port my-container


80/tcp -> 0.0.0.0:28600
443/tcp -> 0.0.0.0:33000

remotet ?
locally

Er ssu now

areiv
yurcan sioply

¤ $ curl http://localhost:28600
Ll
dd

O Display running processes


contain in our awesome

ø
$ docker top my-container çöi
141
OGet
pu memory

Useful analyze
Elx
s to monitor and lor

porential leak
memory
a

$ docker stats my-container

ortant
Ro
FraR
frineninine
Iantubnenth
-
O
ç $ docker inspect
—-format ‘{{NetworkSettings.IPAddress}}’ my-container

142
O
entrypoi
Bypass actual container

s
'
X
Yourimage washes Ofistart

?
it again
o but
.i
withashee :

¤
î
$ docker run --entrypoint "/bin/sh folder/" my-image

7 Now the container is


running so
you can execute
,
,
a shell into it

I debug its configuration for example M

OViewcontainer
detai
's
You can inspect not only IP address but also
't
-
s
others useful informationo

environments variables

Itargunents
$ docker inspect my-container

143
wotch DocherementI Ry

containe
000
is
f
restarting

agairowe
egain

Q C
00

.
8 ) Run container &
display in realtime

related container events

's
$ docker run xxx & docker events
—-filter 'container=$(docker ps -lq)'
ar

Oolast
quiet

O
Ayou
also can

U
w ill print more
information
s Run clocker command in
debug mode

$ docker run -D xxx

w debug : debug mode


-
Öëé
oo 144
Limni
00
Docherignore
C
000

3
~ Define rules & exceptions for files and folders
to be excluded from the build context

Y
Q
T
?
ix OôM --

w
aX =
00
woo
0
D my tag
Ds

-image:
145
- Same as
gitignore but for Docker

dockerigr

?:
.
VS code

bin

vendor

Jenkinsfile
Dockerfile
ogitignore
reditorconfig
*
omd
LICENSE
m

146
Allows not
to
copy l include
- the
in
image
sensitive information

ILport
-
- -

uegs

¤"
98.

¤.".

Lt ---

¤
-

-
-

147
iL
Helps to reduce irages size

.
c
--
- T

148
I

lI Behavior
- -

I
loldil IIulewdan

want
to brildt an
images

,
? EI but hor does it work !
Ro
O
dx $ docker build -t my-awesome-image:1.0.1 .

prictive
reat i e dor te dt
,
ooč

I C
ODOD

sont
il
,
J

Client Server

149
aochoigo
Qtke loilduntixt reation

,
I fello the

Drohefiled xchcle filnc licked in

ooŮ
C
ODDO

E a
What I need Files I need

to to exclude
followldo

ao J
-n
FROM
ncrdastal
~

sensiti
Dockerfile
dockerignore

150
S
The final Docker image

vely files youcank

,
'
verid purdencoayeran ADD

in the Dockerfile

000
C
0000

151
D
Don add

'h
files
then
fondonct
in

need
the build cortext if

Egcreds
Jy
xxivx
d q
Xx J
ixes

¿
d
T
.
my awesome
-
-ing
152
tin

!
000
Dockerfile
Cn
0

oo0
Dockerfile contains
o f set a

instructions that Docker

follow images
to build an

iL
thrugha Dochertile
what to rur
Doche

qhoctron
dofines

153
C lines in a

f
Doclurfile
ourimage
are
ingredients

Mon -
genoise base
Apy image
raspbery how
tw
was
ingredients
- R u p ro i n t
of your
-
cae
.
B}
yurmy

154
Li
00
Cs
0000
rron

To define an instruction that initializes

a Dockerfile

1 FROM instruction 1
-

ODefine the base

-
inag
V

t law FROM

Äl
T
-

YL
IdAE
yeDJM
N
FROM python:3.9.16-slim
...

155
Xi It rossible specify
to

's
the target pearforn
o

çdí FROM --platform linux/arm64 my-image:tag

iL

Aien
is the aulg
iust
purbeform
rection go

, rion
can

156
tinw

!
000
C
00

o0
LABEL

- A alds netadata to an
image
s
( description project 000)

,
version,
TT
LABEL instruction
I

C Ados

to
information
an
image J

I lawLABEL

ly

Äf Tr

FROM my-image:tag

LABEL version="2.0.0"
LABEL description="my text \
in several lines"
LABEL com.scraly.app="My app"

157
L
us LADEL

Cprected
instnction instead

HAINTAINET
of

158
$ It
?
How
to

?
) Display labels of an
image

docker image inspect


--format '{{ .ConfigLabels }}' my-image:tag

- -

is
S Base
image labels urn
's
inherited by your image
L
o

çí

159
"" tirinstrtion
- Defines an
argument that can be passed

at build time

s Allows to override build arguments

- Useful to not hardcode

information in Dockerfile

160
?

How IX
to

?
O Pass
image name and version

& override values in Dockerfile

ARG MY_IMAGE=golang
ARG VERSION=latest
FROM $MY_IMAGE:VERSION as build

Y Build golang latest clocker inage


:
$ docker build -t my-image:tag .

docker
Y Build bitnami l golang alpine 12
image
3.
:
$ docker build -t my-image:tag
--build-arg MY_IMAGE=bitnami/golang
--build-arg VERSION=alpine3.12
.

strction should be defined before the

Winon irstinition nerder tohave

te fron
naggect
.
161
O
a Pass
information to Dockerfile

FROM busybox
ARG user
RUN echo "user is $user"

Y Build
image
with user value

$ docker build -t my-image:tag


--build-arg user=moby
.

L
,
Otheraise
define Anr

Arn have
inctruction

a
after

scopetd
Ahors
=
Yey

,
,
162
2.
It wore but don

ARa

't
use

's
,
i
instructions for sencitive infurmation
L coedentials pass words
o

..,
,
čãí

I Bild variable we visible through


-time
dicker c o n m a n d
history

163
strctimnfur
environment variable
w Defines an that

can be passed at build time

w set environment variables to a container

164
?

Q IY
How to

?
@ Pass an
environment variable
from argument

FROM alpine:latest
ARG PORT_ARG=3000
...
ENV PORT=$PORT_ARG
?
COPY ./package.json .
...

Y Build image & run a container

$ docker build -t my-image:tag .


$ docker run my-image:tag

165
O Pass environment variables to
containe favorite
our
.
FROM golang:1.19
ENV ENV=INT
ENV REGION=eu-central-1
COPY ./entrypoint.sh /app/entrypoint.sh
WORKDIR /app
ENTRYPOINT ["./entrypoint.sh"]

$ docker run
-e "ENV=prod"
-e "REGION=eu-central-1"
my-image:tag
ë
x

Cej
emussame

166
E Pass environment variables from
an environment file

ENV=prod
REGION=eu-central-1

container
Run a

$ docker run --env-file=my-file.env my-image:tag

container
Run a
from busybox image
I display enr variables

$ docker run
-e KEY=VAL
--env-file=my-file.env
busybox env

167
ë
QIY
cv
tips

oreperidedtgwop
Ff pesson sovirnrent woes
ju

though fu the find

-ean-file,
rals ebo the

O Display the content of our environment file

$ cat myfile.env

ENV=prod

O Run
containe a
.2
&
display environment values "
ENV"
equals to

$ docker run -e ENV=qa --env-file=myfile.env


ubuntu:latest env | grep ENV

ENV=prod

168
tuw
000
C
000

copy

-
To
copy localfiles &
directory
in an
image ,
least
specify at ADD Or COPY instructions

in the Dockerfile

Flawo
-

d -
copy law vs ADD

169
-

I
I
I instruction
copy

O files directory
Adds &

a host to an image
from

copy law
t
l
Ir

FROM golang:1.19-alpine

ÄT WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /my-app main.go

CMD [ "/my-app" ]

I ass cony
if
directury
yor Just cautto

into the build


are

context
filiys

170
Eien treaegeaturn
docalveres
oy

tonextraction
I remote URL support

)
Fl ADD 2
wo
Un
F
Äl
FROM busybox:latest
WORKDIR /app

ADD https://go.dev/dl/go1.19.4.linux-
amd64.tar.gz ./

RUN tar -xzf go1.19.4.linux-amd64.tar.gz \


&& rm go1.19.4.linux-amd64.tar.gz

CMD ls -alrt

Allows esray imput as


Gile oran VRL But
.
Lns
be cache it recomne de to
carefue for
's
usage

use wre conmand in RuN ins tructioninstea

171
X Copy is
prefered for basic

.ië
copy "

regictricks"
,
o

čdě

172
Linw
00
Cs
000
ron

s
To define commands to execute

T
instruction
RON I
2

C
fecuke commands

fuse the resuet in

other commands J

tG law
RUN

ÄT
i
r

FROM ubuntu

## Install dependencies
RUN apt update && \
apt install curl cowsay -y

RUN cp /usr/games/cowsay /usr/local/bin/cowsay


173
Il
I HoYork
dees it

?
etdlicdt ludeddan

Build this image

$ docker build -t cowsay .

@ Display the
layers
$ docker image history cowsay

@ Run the container

I execute with
cowsay a
message

$ docker run -it cowsay

hello
rool @ cowsay
aft3elbocf3:~$
____
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||

174
Liwi
CRD
000

:
string uosson

O
00

o0
syntay

TT
instruction
I

s You define CMD instruction in two


can
ways

IIstring
ssoNagutas syutax I

175
-
string
syntax
Z
s Be careful this instruction executes a command

,
with a
shell
h

CMD ["./hello"]

2
/bin/sh -c "./hello"

.
thriconsdhell
incverpivags This

courand can consianerr


.
L
exec: "/bin/sh": stat /bin/sh:
no such file or directory

176
ssörsynta
This command
s h executes ewithout
ll
arguments z
a

CMD ["./my-command"]

- Let take a
look with a concrete example
's
:
FROM golang as build
COPY hello.go .
RUN go build hello.go

FROM scratch
COPY —-from=build /go/hello.
CMD ["./hello"]

s Execute a command with a


different shell

Le bash
.g.
)8
CMD ["bash","-c", "echo $HOME"]

177
000
Lini

Cn E n r ay p o i n t
00

o0
cmD

.
Specifies at least CMD or ENTRYPOINT instructions

in the Dockerfile

ENTRY
instruction

Oour
Defines execurable
when the
container starts J

ENTRYPOINT dw
-
)
l T
r

Ä
FROM my-base-image
...
RUN chmod +x deploy.sh
ENTRYPOINT [ "./deploy.sh" ]

parameter
.
ENTRYPOiNt instruction (
commandf
il
are not ignored when the conmand dockerrun

is executed with parameters 178


instruction
crp

CrD

E Defines executablet poraneters

for a
container

l
2no
I

U L
--
FROM node:alpine
t
I
WORKDIR /usr/src/app
COPY package.json .
RUN npm install —-only=production
!
COPY . .
CMD [npm start]

179
ENTRUPOINTT
WIth

Ir
Defines
cher the
exceutabletorus

container starts

Addoption

.
-

IL
-

I
CMD
ENTRYPOINT

?o
Ät
$ kubectl exec my-pod -it —- ls

r
FROM golang:1.19.4
COPY --from=build /src/bin/redis-tools /redis-tools
ENTRYPOINT [ "/redis-tools"]
CMD [ "--help" ]

180
E L
What happers if Ionly specify
CrD ?
instrct

.
o

çí Implicit entrypoint is /bin/sh -c

ëIMPintd
Chen
woytine orb

yor rn theson
"D
,
,
Kecctabee

181
?

" Ix
How to

?
) Runa container that display Docker
message Ilove

"
a

"s
D
us
-Fempock."
$ docker run -it my-image

container with the the


but overridedefaiet
) Run a same
image
command that allow to runlexec into il
syou

$ docker run -it my-image /bin/bash

instruction
Y Run a container & override ENTRYPOINT

$ docker run my-image —-entrypoint=‘’

182
tini
00
C
000
Expose

-
To define the port & the protocal
D
that the container listens on

instruction
I I

O It lise a docomentation
's
tokronwhich por
publish V

CorIl dwo
EXPOSE

Un

Äl T
-

FROM golang:1.19-alpine

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./

RUN go build -o /my-app main.go

EXPOSE 8080 183


CMD [ "/my-app" ]
IlI
Howork does it

?
lotdiat ludeuedan

FROM my-image:tag

...

EXPOSE 80/tcp
EXPOSE 80/udp

...

d Build this image

$ docker build -t my-image:tag .

D Run the container

I expose
port for TCP and UDP

$ docker run -p 80:80/tcp -p 80:80/udp my-image:tag

184
iL
By defmnet Docher

.
exposes the tep protocoe

185
tuni 000000
C vocomne

To define one or several

mount points

II
VOlUmE instruction

Ccreake two mout point


V

IIl dww
Goo
VOLUme

ÄT T
r

FROM ubuntu

VOLUME myvol myvol2

186
lI t
Howork dees it

?
eolcdinadt lIbodeweden

FROM ubuntu
RUN mkdir /myvol
RUN echo "hello docker lovers" > /myvol/docker
VOLUME myvol

O Build this image

$ docker build -t my-image-with-vol .

187
D Run the container

I verify the existance


of the volume

content docker file


"

and the the


of

"
$ docker run -it my-image-with-vol

aaft Is Imyvol
3elbocf3:~$
docker

root eagazerbocf cat


Inyvolldocker
3:$
hello docker lovers

B List existing volumes

$ docker volume ls

188
"
wolintigue

":
wonsed to
specify l bewan
beforn

-pothes
the difarer wurfing directory within

¤
a Dechertileisl

189
Li

!
00
C
0

oo0
user

-
To define the user name Cf group

)
D
to the default ( group

f
use as user

)
-

-
USER instruction
1

O
Itele which user
,
poptionally group
to use

I laav USER

create
Ä T
-

the user FROM ubuntu:latest


I the t RUN groupadd -r mygroup \
&& useradd -r -g mygroup -ms /bin/bash myuser
group first
USER myuser
WORKDIR /home/myuser
190
II t
Hoõoork does it

?
coldid 11ludeaddon

FROM ubuntu:latest

RUN groupadd -r mygroup \


&& useradd -r -g mygroup -ms /bin/bash myuser

USER myuser Ls
WORKDIR /home/myuser
- 8 user home
directory
m
's
-58 user new shell
's
O Build this image
$ docker build -t my-image-with-user .

191
D Create a container

I
verify you not root but
are
nyuser
I the working directory is
myuser home

s
'
$ docker run -it my-image-with-user

myuser @ aft: ~
$ pud
3elbOcuf3
Ihomel myuser

192
IIf
theuser desr havegour primary

,
the it ad
group by defaret is

L equals
o to root

çdí

Tho nsar wush xich beforn the rean instruaction

h
Gese
,
the suiket camor

193
ti

!
000
C
000
WORKDIR

To define the working directory for


other instructions

1instruction
WORKDIR
I

E
define the working
directory at a
given ster
s

-
L
I
WORKDIR do
aoo
-l
U

Äl e
r

FROM my-image:tag

# My directives
...
WORKDIR /usr/src/app

# Others directives
...
WORKDIR /tmp/ 194
EIf
a vlative path
is defined other paths will

,
bo
ore apended to the previos

o
ar
6
b
-

WORKDIR lv
Im
Ua

Äl i

}
FROM my-image:tag

WORKDIR /my pudo


WORKDIR awesome
Imy I awesomel path
WORKDIR path

RUN pwd

195
iI
f jouden define
WORKDID

't
-

Sy default itis ut to

,
196
Linl

!
00
C
000
orpoins

To define instructions that will be

executed when building a


image
new

1 ONBUILD instruction I
-

C heep fir
I late

these orboics

instruction V

Il ONBUILD
fo daw

ÄT -

FROM node:0.12.6

RUN mkdir -p /usr/src/app


WORKDIR /usr/src/app

ONBUILD COPY package.json /usr/src/app/


ONBUILD RUN npm install
ONBUILD COPY . /usr/src/app

CMD ["npm", "start"] 197


Il
I Howork
does it

?
eldlict ludeddan

Build this image

$ docker build -t node:0.12.6-onbuild .

D Use it in the FRoM instruction


in Docker file
your

FROM node:0.12.6-onbuild
#
...

D
Buildy
image our

$ docker build -t node:0.12.6-mine .

C
Thes wuiBvild instructions

eftte irage re ececuteds fustaftergur


-basn
instruction
apern

¤
198
L
uesefue when tho

a
inage
base image
isused as

199
Linw

'
000
C
00
HEALTHCHECK

o0
s
To define instructions that Docker

needs to test
if a container

is still working

HEALTHCHE
I Iinstruction

O
Hey container
,
wre yustiee
alive V
?
I dw
Cor
HEALTHCHECK
T
2l
-

a FROM golang:1.19-alpine

WORKDIR /app

Äl COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /my-app main.go

HEALTHCHECK CMD curl --fail


http://localhost:8080 || exit 1

CMD [ "/my-app" ] 200


It
HoYworke does it

?
coldult IIledealdad

@
is
container
started
LXS
II
starting
:

!
@

Ä
HEALTHCHEK
instruction is

executed [
Healthy
X
@ !
If instruction r
-
failed x times
D
,
!l*
container become

unhealthy {unhealthy
201
isces
Example

y After a start period of 8 seconds

,
tLeck
oseconds
every

If a check takes longer than 5 seconds it


fails

.
,
After 5
failed retries the container is
unhealthy

.
,
-

1 dw
Cor
HEALTHCHECK
Ll
Ua FROM nginx:1.23.3

Äl HEALTHCHECK --interval=10s --timeout=5s


--start-period=8s --retries=5 \
CMD curl --fail http://localhost:80 || exit 1

EXPOSE 80

yor instirutions
defire
the
Seveol

lack cil
HEALTHCHECK

he tahon in acont
,
202
C
alo oesible to
It 's
fire - HeaetteHacK

irstinction in Pocle coupos


o

a
.
203
Lini
00
C
000
storsiaNaL

-
Override the default signal sent

to a container to exit

SThe
IGTE
is to
R N
default signal equals

s
IOSQNANES
-

l STOPSIGNAL
-
Ckill
o
{ A NAME tern
Kernelsyscate wober

çdč

204
I storsion
instruction 1

I
o ke s cotainer creil
h signae
the
ner
You need to stop J

STOPSIGNAL lw
-

Äl Tr

FROM my-image:tag
...
STOPSIGNAL SIGQUIT

205
B
jefarero
d
isces

s docker stop command stops any running containers

$ docker stop my-container

Äi

O
send SIGTERM signal
Wait lo seconds by
L default

signal
send sigkill

âq

Ok butooo

206
-\
I-
How does it
work

?
losulind Hluduullan
1
Build this image

$ docker build -t my-app .

D start a container

$ docker start my-app

B stop the container

$ docker stop my-app

STOPSIGNAL law
-

l SiGKiLl

ÄT
207
Linwl

!
000
CP
000 SHEw

Default shell on Linux is I "-

"lbinlsh",
c"]
I and
"

& "1 J

Is",
Windows

c"
on is

,
",
"
SHELL verride
shells the default

-instruction 1
SHELL
-

d --
SHELL
law
la
Äf
FROM windowsservercore

# Executed as cmd /S /C echo default


RUN echo default
i
-
# Executed as cmd /S /C powershell -command Write-Host default
RUN powershell -command Write-Host default

# Executed as powershell -command Write-Host hello


SHELL ["powershell", "-command"]
RUN Write-Host hello

# Executed as cmd /S /C echo hello


SHELL ["cmd", "/S"", "/C"] 208
RUN echo hello
ëL
cesufue for Windous
have to
because

nation sheel
the os

209
Liwli
000 Dockerfile
CB
0000

tirs

ëlfï
the Dockerfile with
different
manners

Several tips exist to reduce the size

210
Smaller images
z

Ş
builds
Faster

Faster
F
deploys
s
smaller attack surface
,
211
s nerge multiple Run statements into

single one :

RUN apt-get update


RUN apt-get install -y nginx

)
RUN apt-get update \
&& apt-get install -y nginx

X layers
Reduce

to reduc size

čd

212
Or I Squash at the end of the build

$ docker build --squash -t my-image .

E
Allows to merge all

filesystem layers in
onlyone

"
Diiiii 213
Use Distroless base
image
?
S To reduce
image sice
.i
Nhardkn
it

Qv
T
blo

your app
A

runtime dependencies

FROM gcr.io/distroless/nodejs18-debian11

wh
y
?
a
o small images
venerabilities
Avoiding
surface less attack
language for different
.
Existing images

214
pistorlean
ubspalitW
a
beimpoirtiyroing

tnburhnashe

FROM gcr.io/distroless/nodejs18-debian11
...
CMD ["/app"]

215
SMuti
e build

-stages
in
one Docherfile
Only where

& Runtime environments


we
define Build

-
As
Fon

Dockerfile

IT
suiedenniement
II
tnatinecuinoment

216
-
Allows to
copy artifacts from
one
stage to another

II rnibuild IIT
lony

muntinecoioonent
biedonierunt

name
of the stage
# Build env I
FROM maven:3-jdk-11 AS build
COPY src /app/src
COPY pom.xml /app
RUN mvn -f /app/pom.xml clean package

# Runtime env
FROM gcr.io/distroless/java:11
COPY --from=build /app/app.jar /usr/app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/usr/app/app.jar"]

L Images contair wnly


to
they provide a
apps

vinival
a dependancing
attack
surface
.
217
S possiblet
It build

-
's
aspecified stage
.
o

çdí $ docker build --target build -t my-image:tag .

E Ob but why

?
,
V Debugging a
stage

stage Using a
debug
with tools 000

stage
Using test a

with fake data


000
o ooo

218
C
Anortifactcanse
upied from an ixternal
inage

¤
FROM my-image:tag
...
COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf

Kit only needed built


With
Build stages are
,
FROM my-image:tag AS base
RUN echo "hello from base"

FROM base AS stage1


RUN echo "hello from stage1"

FROM base AS stage2


RUN echo "hello from stage2"

Let build only base f staged


G
's
$ DOCKER_BUILDKIT=1 docker build --no-cache --target stage2 .
,
219
S FRoM scratch

s To build base images

( busybox 000)

debian,
minimal
images
or

Conly one
binary

)
FROM scratch
COPY hello /
CMD ["/hello"]

220
Linwi
00
G conrose
000

s Handle several containers at once

container u
iA y confiration
's
called a service

- Services are
defined in a

docker yme file


-compose.
ë

In
flurch line in ducbur yre
every
a
-compose
file corresponds to Docher cormand
221
IT
HoYworkl does it

ludel IIloluudad
I build my own
image

1
$ clocker buildit
cowsay myappl
services:
T
my-app: ?
I
build:
context: ./myapp
dockerfile: Dockerfile

I
image: cowsay:latest
container_name: my-app
D ocker ports:
- 8080:5000 expose port
5000 of the
willcreate db: container port 8080
on

2 containers image: my-db:1.0.0 in the host


...
image I puel
existing
1
docker pull
1.00 my
-db:
Xny
-app
EFdb
222
-
Volumes can be local
s
( in one container

accessible
)
& global
laccessible by all containers

)
services:
myapp-with-vol:
image: my-image:tag
volumes:
- my-global-volume:/the-global-volume read
- /my-folder:/vol-in-readonly:ro only volume
my-second-app-with-vol: L only for
image: alpine:latest
my

,
volumes:

-app-with-vol
- my-global-volume:/another-path/the-global-volume
volumes:
my-global-volume:
global volume
( accessible
by
s
all containersl services

Ql my

dee
-global-volume
?
t ripranth
-ne
I the
-global-volume
B vol in
readonly
-
-
1
_
T
my
-second-app-with-vol
Ql another the
-glo
-pathl
223
"
It possible to ask Docker

's
to startIhandle a service
after
another one

services:
@ myapp:
image: my-image:tag
depends-on:
- db
@ db:
image: my-db:latest

- Insted of having 1 service :1 container


s
,
the number
you
can
define of containers

service
per

services:
myapp:
image: my-image:tag
deploy:
mode: replicated
replicas: 6

óîôâó
ûfûfØi
{n
224
E
Abot of ther featurs
exists Doche Compose
.
on

čdŽ

225
?

Q IY
How to

?
I start the services

$ docker compose up

I start the services in


background
$ docker compose up -d

I Display running
services

$ docker compose ps

I stop the services

$ docker compose stop

services Remove the volumes I created

$ docker compose down --volumes

226
Liwi
00
C
0000 Extensions

- Extends Docker Desktop

Extensions
i n are accessible

the Marketplace

i
E
install
you can
yor
oun extencions "

çdž
227
IT
Howorke does it

?
ludlil IIboluudad
-
An extension is composed of several
required
files and folders :

_
mradatorisca Dockerfile
everything
!
{
you
need to
O u

:
build the

à
extension

Lörime
information
about

the extension 8

OV name
UIlfront
index
path to
file of the

extension
path
ui
xxx sug

\, an icon

228
?

" IY
How to

?
Initialize extension
y a new

$ docker extension init my-extension

Build extension
) your

$ docker build -t myuser/my-extension:1.0.0


t
DockerHab user
your

} Install
your
extension

$ docker extension install myuser/my-extension:1.0.0

} update the extension

$ docker extension update myuser/my-extension:1.0.0

I list installed extensions

$ docker extension ls

229
extension
Remove an

$ docker extension rm myuser/my-extension:1.0.0

I Validate your
metadata Json file

.
$ docker extension validate metadata.json

230
Li

!
00
tooes
CB
000

Tl
l l dive

-
C
'
Examine filesystem changes between

different layers of your images .

https://github.com/wagoodman/dive

Usage
$ dive gcr.io/distroless/java

or 8

$ dive build -t my-image .

In CIICD chain

CI=true dive my-image

231
Tl
5 N J

Thub l
uexperimental

-tooe
- with Desktop 3.0

CC

Interact with Docker Hlub

through a CLI
5 )

& limits
Dis play user
information user

$ hub-tool account info

Display user rate limiting


$ hub-tool account rate-limiting

List repositories
my
$ hub-tool repo ls

Show tags for repository


$ hub-tool tag ls scraly/simpleapp —format=json

Remove I toto
my repository scraly
$ hub-tool repo rm scraly/to to —force

232
LTT
Ttshopeo

"'

Handle many operations


to containers images 7)

https://github.com/containers/skopeo

- Handle different containers registries

7IY
FTE
A
Ovay
[T.%8wY*Y.%
Google
JFros Artifactory HARBOR container

Registry
ss Don root user =
't
run as

233
Login
$ skopeo login my-registry.com -u my-user

Copy an
image from Dockertlub to

my private registry
$ skopeo copy docker://dockersamples/k8s-wordsmith-web
docker://my-registry.com/dockersamples/k8s-wordsmith-
web

remote
Delete an
image from a
registry
$ skopeo delete docker://my-registry.com/my-image:my-tag

Inspect a remote image ( to pull it


noneed
!)
$ skopeo inspect docker://my-registry.com/my-image:my-tag

between registry and folder


Synchronize images a a

$ skopeo sync --src docker --dest dir


my-registry.com/busybox /my/folder

234
Tl
l l trivy
-

kcanne
CL
slnsters
security
i

,So.
containers
,
https://github.com/aquasecurity/trivy

- Vulnerabilities detection
:
O of os
packages
V Application dependencies
" yarn cargo pipenv composer bundler 000)
,
pm,
,
,
,
nisconfiguration
derection

( Docker Terraforn o
00)
Kuberneres,
,
7 Secret derection

simple
and fast scanner

CI
Easy integration for
- A Kubernetes operator 235
s
Scan an
image
$ trivy image python:3.11-alpine

Scan and save in a


JsoN report
$ trivy image golang:1.19-alpine -f json -o results.json

236
Inthesamecoeeec

|AvailableonPaperba÷Ama /
¥

& on
digital on Gum road

Youtube
https://www.youtube.com/AurelieVache
237
whom
DevRel D
y p
Devops 7
years

+1
)
r
t Google Developer Expert in cloud technologies
ü
Me
1g!*
"Y"säY.
conference organizers I nentor

kook
- Technical writer Speaker O I

.
a sketchnoter

Contact me
Aurélie Vache -

JB Caurelievache
SJ
""
Abstra
understanding Docker can be difficult or
time

-consuming.
I created this collection of sketchnotes about Docker

in order to
try to explain the technology in a visual
way
.
niluded
V Docker components
V Resources

V concretes examples
W Tips & Tools

You might also like