N docker cheat sheet: images and containers, the dockerfile, ports, volumes and compose - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/docker-cheat-sheet/
☷ docker cheat sheet: images and containers, the dockerfile, ports, volumes and compose - nicnonac guides _□×

← back to guides

docker cheat sheet: images and containers, the dockerfile, ports, volumes and compose

Stacks · 14 min read · posted Nov 30, 2026, 9:45 pm

Most of the Docker you use day to day comes down to five things: images and containers, the Dockerfile, ports, volumes, and compose. Once you can picture what each one does, the commands stop being guesswork.

This is the cheat sheet from the reel. For each of the five you get when you'd reach for it, the commands with what they printed, the mistake that usually bites, and something to practise on. There's a quick lookup table first, and a note on how a container, an image and a volume differ.

Every command here was run for real, and the output under it is what came back. The setup: Docker Engine 29.5.2 with the docker CLI 29.7.2 and Docker Compose 5.5.0, on a Mac with Apple silicon, with the engine running in a Linux VM (Colima). Three things were tidied, and only these: long ids are cut to their first 12 characters and end in …, the colour codes some programs print are taken out, and the layer by layer download progress of one image pull is left out (section 5 says where).

One thing will look different on your machine. This setup has no buildx plugin, so docker build used Docker's older classic builder, which prints Step 1/6 lines and Using cache, and starts with a notice that it's deprecated. Docker Desktop builds with BuildKit, which lays the same steps out differently and marks a reused step CACHED. The steps, the order and what gets reused are the same.

All five sections use one small Python web app. These are the three files, in a folder called app:

app.py

from flask import Flask

app = Flask(__name__)


@app.get("/")
def hello():
    return "hello\n"


app.run(host="0.0.0.0", port=80)

requirements.txt

flask

Dockerfile

FROM python:3.13-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install \
    -r requirements.txt
COPY app.py .
CMD ["python", "app.py"]

the quick lookup

i want to ... run
build an image from the Dockerfile in this folder docker build -t web .
see an image docker images web
see the layers an image is made of docker history web
start a container from an image, in the background docker run -d --name web1 web
start one and publish a port docker run -d --name web1 -p 8080:80 web
see which ports a container publishes docker port web1
see running containers docker ps (narrow it with --filter name=web)
see stopped ones too docker ps -a
read what a container printed docker logs web1
run a command inside a container docker exec web1 ls
open a shell inside a container docker exec -it web1 sh
stop a container docker stop web2
delete a stopped container docker rm web2
delete a running one docker rm -f web1
make a named volume docker volume create notes
mount it in a container docker run -v notes:/data ...
list or delete volumes docker volume ls, docker volume rm notes
start everything in compose.yaml docker compose up -d
see compose's containers docker compose ps
read one service's output docker compose logs web
run a command in a service docker compose exec cache redis-cli ping
stop and remove what compose started docker compose down
delete an image docker rmi web

container vs image vs volume

thing what it is how long it lives
image a read-only stack of layers: a filesystem plus the command to start with. docker build makes one, or it's downloaded the first time you use it until you delete it with docker rmi
container one running (or stopped) copy of an image, with its own writable layer on top until docker rm. Anything it wrote outside a volume goes with it
volume storage Docker keeps outside any container, mounted at a path inside one until docker volume rm. Deleting a container doesn't touch it

The short version: an image is the recipe, a container is one thing cooked from it, and a volume is where the leftovers go so they're still there tomorrow. You can start as many containers from one image as you like, and they don't share files unless you give them the same volume.

1. images and containers

When you reach for it. Every time. You build (or pull) an image once, then start containers from it whenever you need the app running.

The idea. docker build reads the Dockerfile and makes an image. docker run starts a container from an image. Each docker run makes a new container, so two runs of the same image give you two separate copies of the app, each with its own name.

The commands. The first build runs every step, so it shows pip installing Flask:

$ docker build -t web .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
            Install the buildx component to build images with BuildKit:
            https://docs.docker.com/go/buildx/

Sending build context to Docker daemon  4.096kB
Step 1/6 : FROM python:3.13-alpine
 ---> 9ef1a599f863
Step 2/6 : WORKDIR /app
 ---> Running in b616f698a093
 ---> Removed intermediate container b616f698a093
 ---> 6fbd8a0e0ad7
Step 3/6 : COPY requirements.txt .
 ---> 6bcfa0fc04ac
Step 4/6 : RUN pip install     -r requirements.txt
 ---> Running in 39dbb88535c5
Collecting flask (from -r requirements.txt (line 1))
  Downloading flask-3.1.3-py3-none-any.whl.metadata (3.2 kB)
Collecting blinker>=1.9.0 (from flask->-r requirements.txt (line 1))
  Downloading blinker-1.9.0-py3-none-any.whl.metadata (1.6 kB)
Collecting click>=8.1.3 (from flask->-r requirements.txt (line 1))
  Downloading click-8.5.1-py3-none-any.whl.metadata (2.6 kB)
Collecting itsdangerous>=2.2.0 (from flask->-r requirements.txt (line 1))
  Downloading itsdangerous-2.2.0-py3-none-any.whl.metadata (1.9 kB)
Collecting jinja2>=3.1.2 (from flask->-r requirements.txt (line 1))
  Downloading jinja2-3.1.6-py3-none-any.whl.metadata (2.9 kB)
Collecting markupsafe>=2.1.1 (from flask->-r requirements.txt (line 1))
  Downloading markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl.metadata (2.7 kB)
Collecting werkzeug>=3.1.0 (from flask->-r requirements.txt (line 1))
  Downloading werkzeug-3.1.9-py3-none-any.whl.metadata (4.1 kB)
Downloading flask-3.1.3-py3-none-any.whl (103 kB)
Downloading blinker-1.9.0-py3-none-any.whl (8.5 kB)
Downloading click-8.5.1-py3-none-any.whl (126 kB)
Downloading itsdangerous-2.2.0-py3-none-any.whl (16 kB)
Downloading jinja2-3.1.6-py3-none-any.whl (134 kB)
Downloading markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl (23 kB)
Downloading werkzeug-3.1.9-py3-none-any.whl (228 kB)
Installing collected packages: markupsafe, itsdangerous, click, blinker, werkzeug, jinja2, flask

Successfully installed blinker-1.9.0 click-8.5.1 flask-3.1.3 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.4 werkzeug-3.1.9
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.

[notice] A new release of pip is available: 26.2.2 -> 26.3
[notice] To update, run: pip install --upgrade pip
 ---> Removed intermediate container 39dbb88535c5
 ---> 82a7a939e4b7
Step 5/6 : COPY app.py .
 ---> 242adb499144
Step 6/6 : CMD ["python", "app.py"]
 ---> Running in 299df0483ee5
 ---> Removed intermediate container 299df0483ee5
 ---> 9780f5749441
Successfully built 9780f5749441
Successfully tagged web:latest

The image is now on your machine under the name you gave it with -t:

$ docker images web
IMAGE        ID             DISK USAGE   CONTENT SIZE   EXTRA
web:latest   9780f5749441       97.1MB         23.4MB

Two containers from the same image. -d starts each one in the background and prints its id:

$ docker run -d --name web1 web
8408cb4dacc0…
$ docker run -d --name web2 web
36e52a9a7d19…

docker ps lists the running containers. This machine had other containers running too, so the list below is narrowed to these two with --filter:

$ docker ps --filter name=web
CONTAINER ID   IMAGE     COMMAND           CREATED                  STATUS                  PORTS     NAMES
36e52a9a7d19   web       "python app.py"   Less than a second ago   Up Less than a second             web2
8408cb4dacc0   web       "python app.py"   Less than a second ago   Up Less than a second             web1

The newest is listed first. A container in the background still has output, and docker logs shows it. docker exec runs a command inside a running container:

$ docker logs web1
 * Serving Flask app 'app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:80
 * Running on http://172.17.0.2:80
Press CTRL+C to quit
$ docker exec web1 ls
app.py
requirements.txt

What bites. Names have to be unique, and a stopped container still holds its name. Running the same docker run --name web1 again fails until the old container is deleted:

$ docker run -d --name web1 web
docker: Error response from daemon: Conflict. The container name "/web1" is already in use by container "8408cb4dacc0…". You have to remove (or rename) that container to be able to reuse that name.

Run 'docker run --help' for more information

docker stop asks the app to exit, waits, and kills it if it hasn't gone after 10 seconds. This Flask app doesn't exit when asked, so the stop below took about 10 seconds, and the status shows exit code 137, which means it was killed. The stopped container is still there until you remove it:

$ docker stop web2
web2
$ docker ps -a --filter name=web
CONTAINER ID   IMAGE     COMMAND           CREATED          STATUS                                PORTS     NAMES
36e52a9a7d19   web       "python app.py"   12 seconds ago   Exited (137) Less than a second ago             web2
8408cb4dacc0   web       "python app.py"   12 seconds ago   Up 12 seconds                                   web1
$ docker rm web2
web2

And a running container can't be removed until it's stopped, unless you force it with -f:

$ docker rm web1
Error response from daemon: cannot remove container "web1": container is running: stop the container before removing or force remove
$ docker rm -f web1
web1

Practise.

  • Start three containers from the web image, named a, b and c. List them, stop b, and list them again with and without -a.
  • Run docker exec web1 python --version. Which Python is that, and where did it come from? (The FROM line of the Dockerfile.)
  • Try docker run web without -d. Your terminal is now attached to the app. Open a second terminal and stop it from there with docker ps and docker stop.

2. the dockerfile

When you reach for it. You want your own app in an image, not just someone else's.

The idea. Each line of a Dockerfile is a step, and each step makes a layer on top of the last one. Docker keeps those layers. On the next build it checks each step in order, and while nothing a step depends on has changed, it reuses the layer from last time instead of running it again. The first step whose input changed runs for real, and so does every step after it.

That's why the Dockerfile above copies requirements.txt and installs it before it copies app.py. Your code changes all the time, your dependencies rarely do, so the slow install stays cached.

The commands. Change the reply in app.py from "hello\n" to "hello from web\n" and build again:

$ docker build -t web .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
            Install the buildx component to build images with BuildKit:
            https://docs.docker.com/go/buildx/

Sending build context to Docker daemon  4.096kB
Step 1/6 : FROM python:3.13-alpine
 ---> 9ef1a599f863
Step 2/6 : WORKDIR /app
 ---> Using cache
 ---> 6fbd8a0e0ad7
Step 3/6 : COPY requirements.txt .
 ---> Using cache
 ---> 6bcfa0fc04ac
Step 4/6 : RUN pip install     -r requirements.txt
 ---> Using cache
 ---> 82a7a939e4b7
Step 5/6 : COPY app.py .
 ---> 678d67ae139b
Step 6/6 : CMD ["python", "app.py"]
 ---> Running in fa7e51d8225e
 ---> Removed intermediate container fa7e51d8225e
 ---> e9c8730c1768
Successfully built e9c8730c1768
Successfully tagged web:latest

Steps 2 to 4 say Using cache, so pip didn't run at all. Step 5 copied the new app.py, and step 6 came after it, so it ran again too. docker history lists the layers, newest first. The ones under the WORKDIR line came with the python:3.13-alpine image:

$ docker history web
IMAGE          CREATED                  CREATED BY                                      SIZE      COMMENT
e9c8730c1768   Less than a second ago   /bin/sh -c #(nop)  CMD ["python" "app.py"]      0B
678d67ae139b   1 second ago             /bin/sh -c #(nop) COPY file:f865687a0523b230…   12.3kB
82a7a939e4b7   22 seconds ago           /bin/sh -c pip install     -r requirements.t…   17.1MB
6bcfa0fc04ac   25 seconds ago           /bin/sh -c #(nop) COPY file:a5661e64632eb6b6…   12.3kB
6fbd8a0e0ad7   25 seconds ago           /bin/sh -c #(nop) WORKDIR /app                  8.19kB
9ef1a599f863   3 weeks ago              CMD ["python3"]                                 0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              RUN /bin/sh -c set -eux;  for src in idle3 p…   16.4kB    buildkit.dockerfile.v0
<missing>      3 weeks ago              RUN /bin/sh -c set -eux;   apk add --no-cach…   44.3MB    buildkit.dockerfile.v0
<missing>      3 weeks ago              ENV PYTHON_SHA256=abb0102e6d4ae027509bcb8232…   0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              ENV PYTHON_VERSION=3.13.18                      0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              ENV GPG_KEY=7169605F62C751356D054A26A821E680…   0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              RUN /bin/sh -c set -eux;  apk add --no-cache…   2.91MB    buildkit.dockerfile.v0
<missing>      3 weeks ago              ENV LANG=C.UTF-8                                0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              ENV PATH=/usr/local/bin:/usr/local/sbin:/usr…   0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              CMD ["/bin/sh"]                                 0B        buildkit.dockerfile.v0
<missing>      3 weeks ago              ADD alpine-minirootfs-3.24.4-aarch64.tar.gz …   9.31MB    buildkit.dockerfile.v0

What bites. Copying everything before installing. This slow.Dockerfile does COPY . . first, so any change to any file means the install runs again. The two builds below are filtered with grep to the step lines and pip's last line, and between them the only change was one word in app.py:

FROM python:3.13-alpine
WORKDIR /app
COPY . .
RUN pip install \
    -r requirements.txt
CMD ["python", "app.py"]
$ docker build -t slow -f slow.Dockerfile . 2>&1 | grep -E "^Step|Using cache|Successfully installed"
Step 1/5 : FROM python:3.13-alpine
Step 2/5 : WORKDIR /app
 ---> Using cache
Step 3/5 : COPY . .
Step 4/5 : RUN pip install     -r requirements.txt
Successfully installed blinker-1.9.0 click-8.5.1 flask-3.1.3 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.4 werkzeug-3.1.9
Step 5/5 : CMD ["python", "app.py"]
$ docker build -t slow -f slow.Dockerfile . 2>&1 | grep -E "^Step|Using cache|Successfully installed"
Step 1/5 : FROM python:3.13-alpine
Step 2/5 : WORKDIR /app
 ---> Using cache
Step 3/5 : COPY . .
Step 4/5 : RUN pip install     -r requirements.txt
Successfully installed blinker-1.9.0 click-8.5.1 flask-3.1.3 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.4 werkzeug-3.1.9
Step 5/5 : CMD ["python", "app.py"]

Both builds installed Flask from scratch. With the order in the main Dockerfile, the second one would have reused it. On a real project with a long requirements file, that install is often most of the build time, and this order runs it on every change.

Practise.

  • Add requests to requirements.txt and rebuild. Which steps say Using cache now, and why does pip run again?
  • Run docker history web after each build and watch which layer ids change.
  • Rewrite slow.Dockerfile into the fast order yourself, then check it with two builds and a one-word change to app.py.

3. ports

When you reach for it. The app in the container is a server and you want to reach it from your machine: a browser, curl, another program.

The idea. A container has its own network, so a server listening on port 80 inside it can't be reached from your machine by default. -p 8080:80 publishes it: connections to port 8080 on your machine (the host) are passed to port 80 in the container. The host port comes first, the container port second.

The commands.

$ docker run -d --name web1 -p 8080:80 web
39f88e959bde…
$ docker port web1
80/tcp -> 0.0.0.0:8080
80/tcp -> [::]:8080

docker port shows the mapping, once for IPv4 and once for IPv6. The app answers on the host port (curl was run in a terminal here, so it printed only the reply):

$ curl localhost:8080
hello from web

docker ps shows the same mapping in its PORTS column:

$ docker ps --filter name=web1
CONTAINER ID   IMAGE     COMMAND           CREATED         STATUS         PORTS                                     NAMES
39f88e959bde   web       "python app.py"   2 seconds ago   Up 2 seconds   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp   web1

What bites. Two containers can't both take the same host port. The second one fails to start, and it's left behind in the Created state still holding its name:

$ docker run -d --name web2 -p 8080:80 web
cae4ee8ed57f…
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint web2 (ba45c4d994aa…): Bind for 0.0.0.0:8080 failed: port is already allocated

Run 'docker run --help' for more information
$ docker ps -a --filter name=web2
CONTAINER ID   IMAGE     COMMAND           CREATED                  STATUS    PORTS     NAMES
cae4ee8ed57f   web       "python app.py"   Less than a second ago   Created             web2
$ docker rm web2
web2

Pick another host port. The container port stays 80, because that's where the app listens:

$ docker run -d --name web2 -p 8081:80 web
5f6f35ac7283…
$ curl localhost:8081
hello from web

The other one: an app that only listens on 127.0.0.1 inside the container. The port is published, but the connection from outside arrives on the container's network interface, not on its loopback, so nothing answers. This runs Python's built-in web server bound to 127.0.0.1:

$ docker run -d --name inside -p 8082:80 python:3.13-alpine python -m http.server 80 --bind 127.0.0.1
bdae1e645f60…
$ curl localhost:8082
curl: (52) Empty reply from server
$ docker exec inside wget -qO- 127.0.0.1:80 | head -3
<!DOCTYPE HTML>
<html lang="en">
<head>

From inside the container it works. From the host it doesn't. That's why app.py ends with host="0.0.0.0", which means every interface. If a published port gives you an empty reply or a reset connection, check what address the app inside is listening on.

Practise.

  • Run web three times on host ports 8081, 8082 and 8083 and curl all three. Then run docker ps and read the PORTS column.
  • Start a container with -p 8080:80 and another with -p 9090:80. Which one does curl localhost:8080 reach?
  • Run python:3.13-alpine python -m http.server 80 --bind 0.0.0.0 with -p 8084:80 and curl it. What's different from the 127.0.0.1 run?

4. volumes

When you reach for it. A container writes something you want to keep: a database's files, uploads, a cache. Without a volume it's lost the moment the container is deleted.

The idea. A named volume is storage Docker manages outside any container. -v notes:/data mounts the volume called notes at /data inside the container. Whatever the container writes under /data goes into the volume, and the next container that mounts notes sees it.

The commands. Make the volume, write a file into it from one container, delete that container, then read the file from a brand new one. The first alpine run had to download the image:

$ docker volume create notes
notes
$ docker run --name box -v notes:/data alpine sh -c "echo hi > /data/a.txt"
Unable to find image 'alpine:latest' locally
latest: Pulling from library/alpine
a1c67c46f05a: Download complete
417332e4182f: Download complete
Digest: sha256:f59abe656b69…
Status: Downloaded newer image for alpine:latest
$ docker rm box
box
$ docker run --rm -v notes:/data alpine cat /data/a.txt
hi
$ docker volume ls --filter name=notes
DRIVER    VOLUME NAME
local     notes

--rm deletes the second container as soon as it exits, and the volume is still there.

What bites. Writing somewhere that isn't a volume. The same steps with no -v: the file was written into the container's own layer, so it went when the container did:

$ docker run --name box alpine sh -c "echo hi > /a.txt"
$ docker rm box
box
$ docker run --rm alpine cat /a.txt
cat: can't open '/a.txt': No such file or directory

The other one is a typo in the volume name. -v makes the volume if it doesn't exist, without a word, so note instead of notes hands you a new, empty volume:

$ docker volume create notes
notes
$ docker run --rm -v notes:/data alpine sh -c "echo hi > /data/a.txt"
$ docker run --rm -v note:/data alpine cat /data/a.txt
cat: can't open '/data/a.txt': No such file or directory
$ docker volume ls --filter name=note
DRIVER    VOLUME NAME
local     note
local     notes

If a file you know you saved has vanished, docker volume ls and look for a near-duplicate name. Deleting a volume deletes what's in it:

$ docker volume rm note notes
note
notes

Practise.

  • Make a volume, start a container that appends a line to /data/log.txt with sh -c "date >> /data/log.txt", run it three times, then cat the file from a fourth container.
  • Mount the same volume in two containers at once (both running sleep 300 in the background) and write from one, read from the other.
  • Try docker volume rm on a volume while a container that uses it still exists. Read the error, then remove the container first.

5. compose

When you reach for it. Your app is more than one container: a web server and a database, an API and a cache. Typing out every docker run with all its flags gets old quickly.

The idea. compose.yaml lists the services, each with what it's built from or which image it uses, plus its ports, volumes and settings. docker compose up pulls and builds what it needs, creates a network for the project, and starts every service on it. Services on that network find each other by their service name.

The commands. This compose.yaml sits next to the Dockerfile. web is built from it, cache is a Redis server from the redis:alpine image:

services:
  web:
    build: .
    ports:
      - "8080:80"
  cache:
    image: redis:alpine

The project is named after the folder, app, so the network is app_default and the containers are app-web-1 and app-cache-1. In the output below, the redis:alpine download progress (one line per layer as it downloaded and unpacked) is left out between the Pulling and Pulled lines. Compose also warns about the missing buildx plugin and builds with the classic builder, adding a LABEL step of its own:

$ docker compose up -d
 Image redis:alpine Pulling
 Image redis:alpine Pulled
time="2026-11-30T21:15:38+13:00" level=warning msg="Docker Compose requires buildx plugin to be installed"
 Image app-web Building
 Image app-web Building
Sending build context to Docker daemon     451B
Step 1/7 : FROM python:3.13-alpine
 ---> 9ef1a599f863
Step 2/7 : WORKDIR /app
 ---> Using cache
 ---> 6fbd8a0e0ad7
Step 3/7 : COPY requirements.txt .
 ---> Using cache
 ---> 6bcfa0fc04ac
Step 4/7 : RUN pip install     -r requirements.txt
 ---> Using cache
 ---> 82a7a939e4b7
Step 5/7 : COPY app.py .
 ---> Using cache
 ---> 678d67ae139b
Step 6/7 : CMD ["python", "app.py"]
 ---> Using cache
 ---> e9c8730c1768
Step 7/7 : LABEL com.docker.compose.image.builder=classic
 ---> Running in e3c05796d654
 ---> Removed intermediate container e3c05796d654
 ---> 87c97fc94c56
Successfully built 87c97fc94c56
Successfully tagged app-web:latest
 Image app-web Built
 Image app-web Built
 Network app_default Creating
 Network app_default Creating
 Network app_default Created
 Network app_default Created
 Container app-cache-1 Creating
 Container app-web-1 Creating
 Container app-web-1 Created
 Container app-cache-1 Created
 Container app-cache-1 Starting
 Container app-web-1 Starting
 Container app-cache-1 Started
 Container app-web-1 Started
$ docker compose ps
NAME          IMAGE          COMMAND                  SERVICE   CREATED        STATUS                  PORTS
app-cache-1   redis:alpine   "docker-entrypoint.s…"   cache     1 second ago   Up Less than a second   6379/tcp
app-web-1     app-web        "python app.py"          web       1 second ago   Up Less than a second   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp
$ curl localhost:8080
hello from web

web reaches cache by its service name. Inside the network, cache is a hostname:

$ docker compose exec web python -c "import socket; print(socket.gethostbyname('cache'))"
172.29.0.2
$ docker compose exec cache redis-cli ping
PONG

docker compose logs shows one service's output, each line prefixed with web-1:

$ docker compose logs web
web-1  |  * Serving Flask app 'app'
web-1  |  * Debug mode: off
web-1  | WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
web-1  |  * Running on all addresses (0.0.0.0)
web-1  |  * Running on http://127.0.0.1:80
web-1  |  * Running on http://172.29.0.3:80
web-1  | Press CTRL+C to quit

docker compose down stops and removes the containers and the network it made. The image it built (app-web) stays:

$ docker compose down
 Container app-cache-1 Stopping
 Container app-web-1 Stopping
 Container app-cache-1 Stopped
 Container app-cache-1 Removing
 Container app-cache-1 Removed
 Container app-web-1 Stopped
 Container app-web-1 Removing
 Container app-web-1 Removed
 Network app_default Removing
 Network app_default Removed
$ docker compose ps -a
NAME      IMAGE     COMMAND   SERVICE   CREATED   STATUS    PORTS

What bites. localhost inside a container means that container, not your machine and not the other services. From web, Redis isn't on localhost, so the connection is refused:

$ docker compose exec web python -c "import socket; socket.create_connection(('localhost', 6379))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import socket; socket.create_connection(('localhost', 6379))
                   ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/socket.py", line 868, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.13/socket.py", line 853, in create_connection
    sock.connect(sa)
    ~~~~~~~~~~~~^^^^
ConnectionRefusedError: [Errno 111] Connection refused

Use the service name, cache, as in the gethostbyname line above. The same goes for a database URL in your app's settings: inside compose it's db:5432 (or whatever the service is called), not localhost:5432.

Practise.

  • Add a third service, admin: image: nginx:alpine with ports: - "8081:80", run docker compose up -d, and curl it.
  • Change the reply in app.py, then run docker compose up -d --build. Which steps came from cache?
  • Run docker compose exec cache redis-cli set greeting hi, then docker compose exec cache redis-cli get greeting. Then docker compose down, up -d again, and ask for it once more. Is it still there?

cleaning up

Containers you've removed are gone, but images stay until you delete them. Check nothing is still using an image, then remove it by name:

$ docker ps -a --filter name=web
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
$ docker rmi web slow app-web
Untagged: web:latest
Deleted: sha256:e9c8730c1768…
Deleted: sha256:678d67ae139b…
Deleted: sha256:82a7a939e4b7…
Deleted: sha256:6bcfa0fc04ac…
Deleted: sha256:6fbd8a0e0ad7…
Untagged: slow:latest
Deleted: sha256:d3e122b8b06b…
Untagged: app-web:latest
Deleted: sha256:87c97fc94c56…

Docker also has prune commands that delete everything unused in one go. On a machine where other projects use Docker, read the list of what they'll remove before you agree to it.

how to practise with this

One section at a time, in order: each one leans on the last. Type the commands rather than pasting them, and read every line of output, including the errors. Most Docker problems are explained by the error message, once you know what a container, an image, a port mapping and a volume are.

When something doesn't work, run docker ps -a first. It answers the two most common questions: is the container running at all, and if it stopped, how (the exit code is in the STATUS column). docker logs on that container is usually the second step.

honest limitations

Five things isn't all of Docker. Bind mounts (sharing a folder from your machine with a container), environment variables and .env files, multi-stage builds, health checks, pushing images to a registry, and Docker's other network types all come up soon after these. The Linux commands cheat sheet covers the shell side, which helps once you exec into a container.

The build output here is from the classic builder because of how this machine is set up. With BuildKit it's laid out differently, though the caching works the same way. The ids, IP addresses and timings in the output will be different on your machine.

This app runs Flask's development server, which says so in its logs. It's fine for learning Docker. A real deployment would run it behind a production server.

← all guides

Done nicnonac.com 56.6k