Skip to content
Visual explainer 6h to learn 5 steps

Images, containers, volumes & networks

Run, inspect and debug containers and understand image layers.

By Invicly Tech, , in Full DevOps with Python. About 13 minutes to read.

Topic 13 of 34

In short

An image is a read-only template built from layers; a container is a running instance with its own writable layer. Volumes keep data after containers are removed, and user networks let containers find each other by name.

Think of it like this: An image is a recipe card; a container is a dish cooked from it.

Explained simply

A container is a normal program running on your computer, but fenced off. It sees its own files, its own process list and its own network, so it cannot easily disturb other programs. Docker is the tool that creates these fences and starts the program inside them.

The files a container starts with come from an image. An image is a frozen, read-only bundle: an operating system's basic files, the Python runtime, your libraries and your code. You can start many containers from one image, and each one gets its own private scratch space on top.

That scratch space disappears when you remove the container. So anything you want to keep, like database files, must live in a volume. A volume is storage that Docker keeps outside the container, so a new container can pick up the same data.

Containers talk to each other over Docker networks. If you create your own network and attach two containers to it, each can reach the other simply by its name, for example the API can connect to a database at the host name db.

When something goes wrong, you mostly use three commands: docker ps to see what is running, docker logs to read what the program printed, and docker exec to open a shell inside a running container and look around.

Press Play on a diagram to walk through it one step at a time.

LayersA running container
  1. 1
    Writable container layer

    Changes made at runtime; lost when the container is removed.

  2. 2
    COPY . /app

    Your code; changes most often, so it goes last.

  3. 3
    RUN pip install

    Dependencies; cached while requirements.txt is unchanged.

  4. 4
    COPY requirements.txt

    Copied alone so the install layer stays cached.

  5. 5
    Base image python:3.12-slim

    OS files and the Python runtime.

CompareKeeping data
Named volume
  • Managed by Docker
  • -v pgdata:/var/lib/postgresql/data
  • Best for databases
  • Survives container removal
Bind mount
  • A host folder you choose
  • -v $(pwd):/app
  • Best for live code in dev
  • Depends on host paths
FlowDebugging a container that will not stay up
  1. 1
    docker ps -a

    Find the container and its exit status

  2. 2
    docker logs

    Read the last lines it printed

  3. 3
    docker inspect

    Check exit code, OOMKilled, env and mounts

  4. 4
    Run a shell

    docker run -it --entrypoint sh on the image

  5. 5
    Fix and rerun

    Change the command, env or image and try again

In depth

What a container really is: namespaces and cgroups

A container is not a small virtual machine. There is no second kernel. It is an ordinary Linux process that the kernel has wrapped in namespaces and cgroups.

Namespaces control what the process can see. The PID namespace gives it its own process list, where your app is PID 1. The mount namespace gives it its own file tree (the image). The network namespace gives it its own network interfaces and ports. Other namespaces isolate the host name, users and shared memory.

Cgroups (control groups) control how much the process can use: CPU, memory, number of processes. docker run --memory 512m --cpus 1 sets those limits. If the app goes over the memory limit, the kernel kills it, and docker inspect shows OOMKilled true with exit code 137.

Because containers share the host kernel, they start in well under a second and use little overhead. The trade-off is weaker isolation than a VM, which is why running as non-root matters.

CompareContainer vs virtual machine
Container
  • Shares the host kernel
  • Starts in under a second
  • Isolated by namespaces and cgroups
  • Image is often tens of MB
Virtual machine
  • Runs its own full kernel
  • Boots in seconds to minutes
  • Isolated by the hypervisor
  • Disk image is often several GB

The container lifecycle and what stop really does

docker run is really two steps: docker create builds the container (its writable layer, network and settings), and docker start launches the process. A container stays in the list until you remove it, even after it exits, which is why docker ps -a shows old stopped containers. Use docker run --rm for throwaway containers so they delete themselves on exit.

docker stop sends SIGTERM to PID 1, waits 10 seconds by default, then sends SIGKILL. A well-behaved app catches SIGTERM, finishes current requests and exits cleanly with code 0 or 143. If your app ignores the signal, every stop takes the full 10 seconds and ends in a kill.

A common cause: starting the app with a shell form like CMD uvicorn main:app, which makes /bin/sh PID 1, and the shell does not pass SIGTERM on. Use the JSON exec form, or add --init to run a tiny init process that forwards signals.

  • Exit code 0: clean exit
  • Exit code 137: killed by SIGKILL, often out of memory
  • Exit code 143: stopped by SIGTERM
  • --restart unless-stopped restarts a crashed container automatically
FlowFrom docker run to docker rm
  1. 1
    Created

    Writable layer and settings are prepared

  2. 2
    Running

    PID 1 is your app

  3. 3
    Stop requested

    SIGTERM, then SIGKILL after 10 s

  4. 4
    Exited

    Still listed by docker ps -a, logs kept

  5. 5
    Removed

    docker rm deletes the writable layer

Layers and copy-on-write

An image is a stack of read-only layers. Each layer is a set of file changes, stored once and identified by a hash. Ten images built on python:3.12-slim share the same base layers on disk and in the registry, so only the different layers are downloaded.

When a container starts, the storage driver (overlay2 on most Linux hosts) stacks the image layers and adds one thin writable layer on top. Reading a file finds the highest layer that has it. Changing a file copies it up into the writable layer first; this is called copy-on-write. Deleting a file only hides it with a marker, so files removed in a later Dockerfile step still take space in the image.

The build cache works on the same idea. For each instruction, Docker checks whether it has a layer made by the same instruction on the same parent; for COPY it also compares file checksums. The first changed step and every step after it are rebuilt.

  • docker history myapi:dev shows each layer and its size
  • docker system df shows space used by images, containers and volumes
  • docker image prune removes dangling images

Volumes, bind mounts and tmpfs in practice

Named volumes live under Docker's data folder (/var/lib/docker/volumes on Linux) and are managed with docker volume ls, inspect and rm. If you mount an empty named volume onto a folder that already has files in the image, Docker copies those files into the volume first. Bind mounts do not do this: the host folder simply hides what was there.

The newer --mount flag is more explicit than -v and fails if a bind mount source does not exist, instead of silently creating an empty folder: --mount type=bind,src=$(pwd),dst=/app. Add readonly to stop the container writing to it. A tmpfs mount keeps files in memory only, useful for scratch data that should never touch the disk.

On Docker Desktop for Mac and Windows, containers run inside a hidden Linux VM, so bind mounts cross a file-sharing layer and can be slower than named volumes. File ownership also matters: the container writes files with its own user ID, which may not match yours on the host.

Networking and published ports

Each container gets its own IP address on a Docker network. On the default bridge network, containers can only reach each other by IP. On a user-defined network, Docker runs an embedded DNS server (at 127.0.0.11 inside the container) that answers with container names and network aliases, so db just works.

Publishing a port with -p 8000:8000 makes Docker forward traffic from the host's port 8000 to the container's port 8000. The left side is the host, the right side is the container. By default it listens on all host interfaces, so the port may be reachable from your whole network; -p 127.0.0.1:8000:8000 limits it to your machine.

Containers on the same network talk on the container port directly; publishing is only for traffic coming from outside Docker. Inside a container, localhost means the container itself, not your laptop and not another container.

SequenceA browser request reaching the api, which calls db
Browser on host
Docker port forward
api container
db container
  1. 1GET localhost:8000/items
    Browser on host to Docker port forward: GET localhost:8000/items
  2. 2Forward to api port 8000
    Docker port forward to api container: Forward to api port 8000
  3. 3Resolve db via Docker DNS, connect to 5432
    api container to db container: Resolve db via Docker DNS, connect to 5432
  4. 4Query result
    db container to api container: Query result
  5. 5200 OK with JSON
    api container to Browser on host: 200 OK with JSON

Learn it in 5 short steps

About 1h 10m each. Track them with a timer in your plan.

  1. 1
    Run, stop and remove containers~1h 10m
  2. 2
    Inspect logs and exec into containers~1h 10m
  3. 3
    Understand image layers and caching~1h 10m
  4. 4
    Persist data with volumes and bind mounts~1h 10m
  5. 5
    Connect containers on a user network~1h 10m

Key points

  • Each Dockerfile instruction makes a layer; unchanged layers are reused from cache.
  • Copy dependency files before source code so code edits do not reinstall packages.
  • docker logs and docker exec are the first tools for debugging a container.
  • Containers on the same user-defined network reach each other by container name.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
docker network create appnet
docker run -d --name db --network appnet -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=dev postgres:16
docker run -d --name api --network appnet -p 8000:8000 myapi:dev
docker logs -f api
docker exec -it api sh
docker stop api && docker rm api

The api container reaches the database at host name db.

Find out why a container keeps exiting

Your api container exits a few seconds after starting. Step 1: docker ps -a shows it as Exited (1), so it is not running. Step 2: docker logs api prints the Python traceback; here it says DATABASE_URL is not set. Step 3: docker inspect confirms the exit code and lists the environment variables, and the one you need is missing. Step 4: remove the old container and run it again with -e. If the logs had been empty, you would start a shell in the image instead and run the command by hand.

bash
docker ps -a --filter name=api
docker logs --tail 30 api
docker inspect --format '{{.State.ExitCode}} oom={{.State.OOMKilled}}' api
docker inspect --format '{{json .Config.Env}}' api
docker rm api
docker run -d --name api --network appnet -p 8000:8000 \
  -e DATABASE_URL=postgresql://postgres:dev@db:5432/postgres myapi:dev
# logs empty? open a shell in the image and try by hand:
docker run --rm -it --entrypoint sh myapi:dev

Prove that a volume keeps data after the container is gone

Step 1: start Postgres with a named volume and create a table. Step 2: remove the container completely with docker rm -f. Step 3: start a brand new container with the same volume. Step 4: the table is still there, because the data lives in the volume, not in the container's writable layer. Step 5: only docker volume rm (or docker compose down -v) deletes the data.

bash
docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=dev -v pgdata:/var/lib/postgresql/data postgres:16
sleep 5
docker exec db psql -U postgres -c "CREATE TABLE notes(id int);"
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=dev -v pgdata:/var/lib/postgresql/data postgres:16
sleep 5
docker exec db psql -U postgres -c "\dt"     # notes is still listed
docker volume ls

Quick reference

  • docker run --rm -it python:3.12-slim bash starts a throwaway shell that deletes itself on exit
  • docker ps -a lists stopped containers too; docker rm -f name stops and removes in one step
  • docker logs -f --since 10m api follows only the last 10 minutes of output
  • docker exec -it api sh opens a shell in a running container (use bash if the image has it)
  • docker stats shows live CPU and memory use for each running container
  • -p 127.0.0.1:8000:8000 publishes a port to your machine only, not the whole network
  • Exit code 137 means SIGKILL; check docker inspect for OOMKilled true
  • docker system prune removes stopped containers, unused networks and dangling images

Common mistakes

  • Writing important data inside the container layer, then losing it on docker rm.
  • Using the default bridge network and wondering why names do not resolve.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does docker stop do by default?

Question 2

2Two containers are on the default bridge network. Why can't the api reach the database by the name db?

Question 3

3A container exited with code 137 and OOMKilled true. What is the most likely fix?

Question 4

4Inside the api container, what does localhost:5432 point to?

Question 5

5A Dockerfile step deletes a 200 MB file that an earlier step downloaded. What happens to the image size?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run nginx in the background on host port 8080, check it with curl, read its access log, then stop and remove it.

  2. Exercise 2medium

    Create a user network, start Redis on it, then use a second throwaway container to ping Redis by name.

  3. Exercise 3hard

    Start a container with a 64 MB memory limit, make it use more memory than that, and confirm from docker inspect that it was OOM killed.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between an image and a container?
An image is a read-only template on disk. A container is a running (or stopped) instance of it, with its own writable layer, process and network settings.
Is Docker a virtual machine?
No. On Linux, a container is an isolated process sharing the host kernel. Docker Desktop on Mac and Windows does run a small Linux VM in the background to host those containers.
How do I copy a file out of a container?
Use docker cp container:/path/in/container ./local-path. It works on stopped containers too.
Why does my container exit immediately?
A container lives only as long as its main process. If the command finishes or crashes, the container stops; docker logs usually shows why.

Go deeper

ShareXLinkedInWhatsApp