Docker
A runtime for containers.
A container is basically an isolated user space. Unlike traditional VMs, containers share the same OS.
Layers
A Docker image consists of read-only layers, each of which represents a Dockerfile instruction. Each layer is a delta of the changes from the previous layer. When a container is created from an image, a new writable layer is added on top of the underlying layers.
Storage
Types:
- Volume: stored in a part of the host FS managed by Docker
- Bind mount: stored somewhere on the host FS (non-Docker processes can modify it)
Both use the same -v
flag, the difference is in the first argument:
for a volume, it's the volume name; for a bind mount, it's a local directory path.
Dockerfile
Best practices:
- Use
WORKDIR
instead ofRUN cd ...
- Use multi-stage builds
- Exclude unwanted files from
COPY
with .dockerignore - Reduce the number of layers by minimizing the number of Dockerfile instructions
- Use a separate
RUN
command to download dependencies (e.g.go mod download
): unlike source code, they rarely change, so it's better to cache them in a separate layer
❓ Help
CMD
orENTRYPOINT
?ENTRYPOINT
should be used for the main command,CMD
- for flags/arguments. UnlikeENTRYPOINT
,CMD
can be overwritten from the CLI.
Commands
docker build --tag=<name>:[tag] .
- build an image from Dockerfiledocker run <image> [command]
- create and run a container [with command]--name=<name>
- assign a name to the container--detach
- run the container in background--rm
- remove the container when it is stopped-it
- start a terminal session in the container-p=<host_port>:<container_port>
- forward a port-v=<volume_name>:<container_path>:[mode]
- mount a volume
docker logs [-f] <container>
- print the container's log [and follow]docker exec [-it] <container> <command>
- run a command in the containerdocker ps
- list running containersdocker images
- list downloaded imagesdocker rm <container>
- remove the containerdocker rmi <image>
- remove the imagedocker volume <create|ls|rm>
- manage volumesdocker context <create|ls|rm|use|show>
- manage contexts