Docker image is like an ISO image to install virtual machine in VirtualBox. Docker container is like a virtual machine in VirtualBox.
docker build -t <ImageName> <PathToDockerfile>Example: build a docker image with ubuntu image as the base and ping installed
docker build --tag my-ubuntu-image -<<EOF
FROM ubuntu:22.04
RUN apt update && apt install iputils-ping --yes
EOFThen run it:
docker run -it --rm my-ubuntu-imageThis will run the new image interactively and remove the container after exit the container.
docker run -it <ImageName> --name MyDockerThis will run docker container named "MyDocker" in interactive mode and attaced to a tty so that it won't exit immediately.
- -i: --interactive, run docker interactively, Keep STDIN open even if not attached
- -t: --tty: attach, Allocate a pseudo-TTY for container
- --name: Assign a name to the container
docker start <container-name/ID>docker attach <container-name/ID>
Combine with docker start with docker attach, we can start a stopped container and attach to the running shell.
docker stop <container-name/ID>docker ps # List running containers, it wont' show stopped containers
docker ps -a # List all containers, including stopped containersdocker exec -it <container-name/ID> bashThe command is similar to the combination of docker start and docker attach.
docker start -ai <container-name/ID>docker volume create my-volume # Create a docker volume
docker run -it --rm --mount source=my-volume,destination==/my-data ubuntu:22.04 # Mount the volume
docker run -it --rm -v my-volume:/my-data ubuntu:22.04 # Same as above command but shorterThis will create a volume and mount to /my-data in the docker container, which you can save persistent data.
docker run -it --rm --mount type=bind,source="${PWD}"/my-data,destination=/my-data ubuntu:22.04This will mount my-data in current directory to /my-data in container, and the data will be persistent when you store data in /my-data.
With volume mount, you can't access its data directly in your host system, but it has better performance. With bind mount, you can access the data directly in your host system, but it has poor performance sometimes, especially with lots of read and write.
Combine volume mount and bind mount, example:
# With custom postresql.conf
docker run -d --rm \ # -d: run as deamon
-v pgdata:/var/lib/postgresql/data \ # volume mount
-v ${PWD}/postgres.conf:/etc/postgresql/postgresql.conf \ # bind mount
-e POSTGRESS_PASSWORD=foobarbaz \ # -e: environment variable
-p 5432:5432 \ # -p: map ports from host to container
postgres:15.1-alpine -c 'config-file/etc/postgresql/postgresql.conf' # Run with custom configuration