Understanding Docker: containers, images and volumes
Docker has a few concepts you only need to learn once. After that, you’ll understand every guide that uses it.
The four concepts
- Image: the “package” of a program, like an installation file. You fetch it from a public registry, usually Docker Hub. An image doesn’t change.
- Container: a running instance of an image. You can start multiple containers from one image. If you remove a container, the data inside it is also gone.
- Volume: a place where data is preserved, outside the container. You put everything you want to keep here: settings, databases and files.
- Network: the connection between containers and the outside world.
Your first container
Start a web server that’s reachable on port 8080 of your computer:
docker run -d --name web -p 8080:80 nginx
Then open http://your-server:8080 in your browser. What does the command mean?
-d: run in the background (detached).--name web: give the container a name.-p 8080:80: port 8080 on your computer points to port 80 in the container. On the left is always the port on your own machine, on the right is the one in the container.nginx: the image. It will automatically download if it’s not there yet.
Have a docker run command from a guide and want to make a file from it? Use our tool Docker run to Compose.
The most important commands
docker ps # running containers
docker ps -a # all containers, including stopped ones
docker logs -f web # follow log (Ctrl+C to stop)
docker exec -it web sh # open a terminal in the container
docker stop web # stop
docker start web # start again
docker rm web # remove (data in the container is then gone)
docker images # all images on your computer
docker pull nginx # fetch the latest version of an image
docker volume ls # all volumes
docker system df # how much space Docker is using
Preserving data: volumes and folders
Without a volume, your data disappears if you remove or replace the container, for example during an update. There are two ways:
- Bind mount: a folder from your own computer. Handy because you can see the files yourself and make a backup. Example:
-v /opt/web:/usr/share/nginx/html. - Named volume: Docker manages the location itself. Example:
-v webdata:/usr/share/nginx/html.
Automatic restart
Want a container to automatically restart after a server reboot or crash? Add --restart unless-stopped to your docker run command. It will only stay off if you stop it yourself.
Making containers talk
Containers in the same custom-created network find each other by name: an app can reach a database at db instead of an IP address. With Docker Compose, this happens automatically. So continue reading at Docker Compose.