Docker Cookbok
Quick concepts
Linux containers are a way to create isolated environments that can run code while sharing a single operating system.
- A container is an isolated environment, comprised of binaries and libraries, created on top of an existing OS.
- An image is like a blueprint for a container.
- A Dockerfile is like a recipe for an image
- Docker acts as a mediator between the OS and the containers
- A single OS can run multiple containers
Quick commands
docker container ls
lists all running containersdocker container run <image>:<version>
runs a containerdocker container exec <container name or ID> <command>
runs commands against a containerdocker container cp <source file> <cont name or ID>:<destination path/file>
copies assets from local machine to a container (assets will not be persisted)docker run -v <local files path>:<container files path> <img name>:<img ver>
creates a data volume (-v
): maps a file or folder on the local machine to a destination on the container. This way we can persist files on an imagedocker container exec -it <container name or ID> <chosen shell, i.e. /bin/bash>
attaches a shell to a containerdocker image build --tag <img name>:<img ver> <Dockerfile path>
builds an image from a Dockerfile- Flags
- The
-d
or--detach
flag runs a container in the background - The
-t
or--tag
passes to the build command the name and version of our image
- The
Run a docker container based on an image
# docker container run <image>:<version>
docker container run httpd:2.4
Map ports on a container
# docker container -p <host port>:<container port> run <image>:<version>
# where -p = 'publish ports'
docker container run -p 9999:80 httpd:2.4
If we access http://localhost:9999/index.html
we'll see the server's default test page; we mapped port 9999
on our host to port 80
on the container.
Update an environment variable
docker container exec -it <container name or ID> /bin/bash
PATH=$PATH:<value>
export PATH
Create a Dockerfile
Warning: a Dockerfile must use a capital "D".
FROM httpd:2.4 # the image we're using as a starting point (our image will be based on this image)
EXPOSE 80 # the container port we're exposing
RUN apt-get update && apt-get install -y fortunes # commands we want to execute when building the image
COPY <target path> <destination path> # the specified local files will be copied to the container (subsequent modifications will not be persisted)
LABEL maintainer="moby-dock@example.com" # creator info