Docker Basics: Containers Made Simple
Volumes and Docker Compose
In this lesson you will
- Explain why containers need volumes
- Use a volume or bind mount
- Describe a simple Docker Compose file
Introduction
By default, anything a container writes disappears when the container is removed. That is fine for a web server, but not for a database. Volumes keep data safe, and Docker Compose lets you run several connected containers with one command.
Volumes
A volume is storage managed by Docker that lives outside any single container.
Terminal
$ docker volume create mydata
$ docker run -d --name db -v mydata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=change-me postgres:16-v mydata:/var/lib/postgresql/data connects the volume to a folder inside the container. If you remove and recreate the container, the data in mydata is still there. The -e option sets an environment variable. Use a strong password of your own, not the example one.
A bind mount links a folder from your computer instead. It is handy while developing, because you can edit code on your computer and the container sees the change:
Terminal
$ docker run -p 8080:80 -v "$(pwd)":/usr/share/nginx/html nginxQuick quiz
Why would you use a volume for a database container?
Docker Compose
Real apps often have several parts, such as a web app and a database. Compose describes them all in one file, usually named compose.yaml:
YAML
services:
web:
build: .
ports:
- "5000:5000"
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: change-me
volumes:
- dbdata:/var/lib/postgresql/data
volumes:
dbdata:serviceslists each container.webis built from your Dockerfile, anddbuses a ready-made image.- Compose puts them on the same network, so
webcan reach the database using the namedb. - The
volumessection keeps the database data.
Compose commands
Terminal
$ docker compose up -d # build if needed and start everything
$ docker compose ps # see what is running
$ docker compose logs web # logs from one service
$ docker compose down # stop and remove the containersdocker compose down keeps your named volumes. Add -v only if you really want the data deleted.
Good habits
- Keep secrets out of the Compose file you share. Use an
.envfile that is not committed, or a secrets tool. - Pin versions, such as
postgres:16, rather than relying onlatest. - Do not run containers with more access than they need.
Try it yourself
Write a compose.yaml that runs nginx on port 8080 with docker compose up -d, then take it down again with docker compose down.
Summary
- Containers lose their data when removed, so use volumes for anything that must last.
- Bind mounts share a folder from your computer, which is useful while developing.
- Docker Compose describes and runs several containers together from one file.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading