Comprehensive Docker Tutorial for Beginners (Step by Step)
Docker is a tool that packages an app with everything it needs, its language version, its libraries and its settings, into an image. It then runs that image as a container that behaves the same on any machine. This Docker tutorial for beginners takes you from your first docker run to a Python web app and a MySQL database running together with Docker Compose, in 12 steps.
Every command and every output below came from a real run on my M2 Max, with Docker Desktop 4.98.0, Docker Engine 29.9.2 and Compose v5.6.1. Long outputs are trimmed, and ... marks each cut. Paths show /Users/you in place of my home folder.

That’s the demo app you’ll build, a small page called Visits that counts its visitors in MySQL. You’ll get there by Step 10, one command at a time.
Why do you need Docker?
You need Docker when an app has to run the same way on your laptop, a teammate’s laptop and a server. Three problems push almost every team there.
- Compatibility. One app needs Python 3.12, another needs 3.15, and one machine has to keep both happy. Every upgrade risks breaking the other app.
- Long setup. A new teammate spends a day installing the right versions of everything before they write a line of code.
- Different environments. Your laptop, the test server and production drift apart one small version at a time, and bugs hide in the gaps.
Docker fixes all three the same way. You write down what the app needs once, in a file, and Docker builds the same package from it every time. Each app runs in its own container with its own libraries, on the same machine, without touching the others. A new teammate gets started with one docker run.
For me, Docker means I stop worrying about dependencies. Before Docker, my two big headaches were Python versions that clashed between projects and servers that never quite matched my laptop. Today I run staging and production of a Django app on one VM, each in its own set of containers.
“It works on my machine” finally stops being an excuse, because now your machine ships with the app.
What is a Docker container?
A container is an isolated space where one app runs with its own files, its own processes and its own network. Unlike a virtual machine, every container on a machine shares the host’s kernel, the core of the operating system that talks to the hardware.
Docker builds that isolation from two Linux features. Namespaces give each container its own private view of processes, network and files. Control groups, or cgroups, cap how much CPU and memory a container can use, and Docker changes a container’s cgroup settings when you set those limits.
Containers aren’t meant to host a whole operating system. Each one runs one job, such as a web server, a database or a script, and it lives only as long as that main process runs. You’ll watch one finish and exit in Step 3.
A container runs on its host’s kernel, so a Linux container needs a Linux kernel. That’s why Docker Desktop on a Mac or Windows PC runs the Docker Engine inside a lightweight Linux virtual machine. Ask a Mac and a container for their kernels and you get two different answers.
$ uname -sr; docker run --rm alpine:3.24 uname -sr
Darwin 25.6.0
Linux 7.0.14-linuxkit
The first line is macOS. The second is the Linux kernel inside Docker Desktop’s VM, which is what every container on a Mac actually runs on. Windows containers exist too, and by the same rule they need a Windows kernel. Everything in this tutorial uses Linux containers.
How is a container different from a virtual machine?
A virtual machine is a whole separate computer inside your computer. A program called a hypervisor creates and runs virtual machines, and each one boots its own full operating system, called a guest OS. A container skips the guest OS and shares the host’s kernel, so it’s more like an isolated app than a second computer.
That missing layer is the whole difference in weight. A virtual machine has to boot an entire operating system before your app starts, and it holds a full OS on disk. A container starts a single process. Here’s how small the Alpine Linux image is, the base you’ll use a few times in this tutorial.
$ docker images alpine:3.24
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
alpine:3.24 be2656061b53 13.6MB 4.28MB
It takes 13.6 MB of disk. Starting a container from it, running a command and removing it again took a median of 0.22 seconds over five runs on my Mac, with the command below. Renting a whole apartment to store one bike suddenly looks like a lot of work.
$ docker run --rm alpine:3.24 true
You’ll often use both. Docker Desktop itself runs containers inside a small VM, and my staging and production containers live on a VM too. The VM gives you a server, and Docker splits it into tidy, separate apps.
What is the difference between a Docker image and a container?
An image is a recipe. It holds every ingredient and instruction an app needs, its files, its libraries and its settings. Docker’s own docs call it “a read-only template with instructions for creating a Docker container”.
A container is the dish you cook from that recipe. It’s a running copy of an image, and you can cook as many dishes from one recipe as you like. In Step 8 you’ll run two containers from one image, each with different settings.
You get images from a registry, a library of images. Docker Hub is the public one that Docker uses by default, and it hosts official images for nginx, MySQL, Python, Alpine and thousands more.
What do you need before you start?
- Docker Desktop. Install it for Mac, Windows or Linux. On Windows, use the WSL 2 backend, and my WSL guide covers the Linux side. On a Linux server you can install Docker Engine on its own instead.
- About 2 GB of free disk for the images in this tutorial. MySQL alone takes 1.11 GB.
- A terminal. You don’t need Python on your machine. The app’s Python lives inside its image.
- A folder for the demo. Everything runs from
~/docker-demo, with a few small subfolders you’ll create along the way.
$ mkdir ~/docker-demo
$ cd ~/docker-demo
My Mac also runs containers for other projects, so from Step 3 on, some of my listings add a --filter to show only this tutorial’s containers. On a fresh install you can drop the filter and you’ll see the same rows.
The 12 steps at a glance
Steps 1 to 8 take you from zero to your own image with settings. Steps 9 to 12 add a database, a network, Compose and a registry.
Part 1. Run containers
- Install Docker Desktop and run hello-world.
- Run a web server and open it in your browser.
- List, stop, start and remove containers.
- Pull, tag and remove images.
- Open a shell inside a container.
Part 2. Build your own images
- Write your first Dockerfile.
- Containerize a small Python web app.
- Configure the app with environment variables.
Part 3. Keep data and connect containers
Part 4. Compose and sharing
Step 1. Install Docker Desktop and run hello-world
Install Docker Desktop from the links above and open it. Wait until it says the engine is running, then check both tools in a terminal.
$ docker --version
Docker version 29.9.2, build a82e528
$ docker compose version
Docker Compose version v5.6.1
Compose is docker compose, with a space. The old docker-compose with a hyphen is the standalone legacy version, and Docker Desktop already includes the new one.
Now run your first container.
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
58dee6a49ef1: Pulling fs layer
58dee6a49ef1: Download complete
58dee6a49ef1: Pull complete
c3bdf82c34d1: Download complete
Digest: sha256:c567b231f65614688711a75f31518a064258a51d442117a3e771a3a8fdba78ef
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(arm64v8)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
That’s the whole loop in one command. You typed into the Docker client, the docker command. It asked the Docker daemon, the background service that does the real work (also called Docker Engine), to find the image. The daemon didn’t have it, so it pulled it from Docker Hub, made a container from it and streamed the output back to you.
Notice the first line. You asked for hello-world and Docker looked for hello-world:latest. When you leave out the tag, Docker assumes latest.
Step 2. Run a web server and open it in your browser
nginx is a popular web server, and it makes a good first real container.
$ docker run -d -p 8080:80 --name web nginx:1.30
...
Digest: sha256:66b50d24288dba67f3d000b31223daefc4868c58d29aaacb6a4ff9771597b5eb
Status: Downloaded newer image for nginx:1.30
398423d33a7bd4515231b7a34bafa5bc66251682a2cda01fd13c6600970ff900
Each part of that command does one job.
-druns the container in the background and prints its ID.-p 8080:80maps port 8080 on your machine to port 80 inside the container. The left number is your machine, the right number is the container.--name webgives the container a name you can type later.nginx:1.30is the image and its tag, here nginx 1.30.
Open http://localhost:8080 in your browser and you’ll see the nginx welcome page. The terminal agrees.
$ curl -s http://localhost:8080 | grep "<title>"
<title>Welcome to nginx!</title>
Why does a container need a port mapping?
Every container gets its own IP address on a private network that Docker manages. That address only works from inside Docker’s own setup, so the rest of the world, including your browser, can’t use it. A port mapping opens a door on your machine and forwards anything that knocks to the container.
One door can only lead to one room, though. Try to map the same port twice and Docker refuses.
$ docker run -d -p 8080:80 --name web2 nginx:1.30
c13a7e34d1d3f7177f8c36d257785e75c91951d475246124e4eedf36a6e00915
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint web2 (4f88d97bd510d2a6ebe54b3c2df18bdc05149015cfcf9701fbc9424654e34eaf): Bind for 0.0.0.0:8080 failed: port is already allocated
Run 'docker run --help' for more information
Docker still created the container. It just couldn’t start it, like a restaurant that seats you and then mentions the kitchen is closed.
$ docker ps -a --filter name=web2
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c13a7e34d1d3 nginx:1.30 "/docker-entrypoint.…" Less than a second ago Created web2
$ docker rm web2
web2
Step 3. List, stop, start and remove containers
docker ps lists running containers. I add --filter ancestor=nginx:1.30, which means “made from this image”, so only this tutorial’s nginx containers show up.
$ docker ps --filter ancestor=nginx:1.30
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
398423d33a7b nginx:1.30 "/docker-entrypoint.…" Less than a second ago Up Less than a second 0.0.0.0:8080->80/tcp, [::]:8080->80/tcp web
Start a second nginx container without --name and see what Docker calls it.
$ docker run -d nginx:1.30
f0601d5997de01631e32c3500d18b55903dc51be5b8dd79adcdc6983cdae4249
$ docker ps --filter ancestor=nginx:1.30
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f0601d5997de nginx:1.30 "/docker-entrypoint.…" 1 second ago Up Less than a second 80/tcp infallible_spence
398423d33a7b nginx:1.30 "/docker-entrypoint.…" 1 second ago Up Less than a second 0.0.0.0:8080->80/tcp, [::]:8080->80/tcp web
Skip --name and Docker makes up a name for you, here infallible_spence. It’s charming exactly once. Name your containers.
Stop it, and docker ps stops listing it. Add -a to see stopped containers too.
$ docker stop infallible_spence
infallible_spence
$ docker ps -a --filter ancestor=nginx:1.30
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f0601d5997de nginx:1.30 "/docker-entrypoint.…" 1 second ago Exited (0) Less than a second ago infallible_spence
398423d33a7b nginx:1.30 "/docker-entrypoint.…" 1 second ago Up Less than a second 0.0.0.0:8080->80/tcp, [::]:8080->80/tcp web
Exited (0) means the main process ended without an error. Start it again, then try to remove it while it runs.
$ docker start infallible_spence
infallible_spence
$ docker rm infallible_spence
Error response from daemon: cannot remove container "infallible_spence": container is running: stop the container before removing or force remove
$ docker rm -f infallible_spence
infallible_spence
docker rm only removes stopped containers. -f stops and removes in one go.
Why does a container stop on its own?
A container lives only as long as its main process. nginx keeps running, so its container keeps running. A command that finishes takes its container down with it.
$ docker run alpine:3.24 echo "This container did its job"
...
This container did its job
$ docker ps -a --filter ancestor=alpine:3.24
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
683b6fc5d11e alpine:3.24 "echo 'This containe…" 1 second ago Exited (0) Less than a second ago stoic_poincare
$ docker ps -a --filter ancestor=hello-world
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a48a121e5f60 hello-world "/hello" 10 seconds ago Exited (0) 9 seconds ago interesting_tharp
The hello-world container from Step 1 exited the same way. Both are done, so remove them by name. docker container prune removes all stopped containers at once, which is handy on a fresh install and a bad surprise on a machine with other projects.
$ docker rm stoic_poincare interesting_tharp
stoic_poincare
interesting_tharp
How do you see what a container is doing?
docker logs shows what the container printed. For nginx, that’s one line per request.
$ docker logs --tail 3 web
2026/11/03 17:22:07 [notice] 1#1: start worker process 40
192.168.65.1 - - [03/Nov/2026:17:22:07 +0000] "GET / HTTP/1.1" 200 896 "-" "curl/8.7.1" "-"
192.168.65.1 - - [03/Nov/2026:17:22:07 +0000] "GET / HTTP/1.1" 200 896 "-" "curl/8.7.1" "-"
docker inspect prints everything Docker knows about a container as JSON. A -f template picks out one value, such as its IP address.
$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web
172.17.0.2
$ curl -sS --max-time 3 http://172.17.0.2
curl: (28) Connection timed out after 3005 milliseconds
That address exists, but your Mac can’t reach it, because on a Mac it lives on a bridge inside Docker Desktop’s VM. That’s exactly what the -p 8080:80 from Step 2 is for.
Step 4. Pull, tag and remove images
docker pull downloads an image without running it. Grab the newer nginx 1.31 next to 1.30.
$ docker pull nginx:1.31
...
Digest: sha256:5ab5b0b01097420873a3f3330f44248e34a3c2a3e8d5ee30658aeae8cb7435da
Status: Downloaded newer image for nginx:1.31
docker.io/library/nginx:1.31
docker images lists the images on your machine.
$ docker images nginx
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
nginx:1.30 66b50d24288d 260MB 64.8MB U
nginx:1.31 5ab5b0b01097 261MB 65.1MB
Docker Engine 29 changed this table to a new default view. It lists each tag with its ID and its size. The U under EXTRA sits on nginx 1.30, the image web runs from, and the 1.31 image that no container uses has none.
A tag is a label that points at an image. docker image tag adds a second label, and both labels share one ID.
$ docker image tag nginx:1.30 my-nginx:1.0
$ docker images my-nginx
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
my-nginx:1.0 66b50d24288d 260MB 64.8MB U
docker rmi removes a tag. When the last tag goes, the image goes too.
$ docker rmi nginx:1.31
Untagged: nginx:1.31
Deleted: sha256:5ab5b0b01097420873a3f3330f44248e34a3c2a3e8d5ee30658aeae8cb7435da
$ docker rmi my-nginx:1.0
Untagged: my-nginx:1.0
The first command untagged and deleted nginx 1.31. The second only untagged my-nginx:1.0, because nginx:1.30 still points at the same image. Docker also won’t delete an image that a container uses.
$ docker rmi nginx:1.30
Error response from daemon: conflict: unable to delete nginx:1.30 (must be forced) - container 398423d33a7b is using its referenced image 66b50d24288d
Pin a version tag like nginx:1.30 in anything that matters. latest means “whatever was newest when you pulled”, which is a different image next month.
One cleanup command deserves a warning. docker image prune -a removes every image that no container uses. On a machine with other projects, read what it lists before you say yes.
Step 5. Open a shell inside a container
-it gives you a terminal inside a new container. It’s two flags. -i keeps STDIN open so the container can read what you type, and -t gives it a terminal so you see a prompt. --rm removes the container when you exit.
$ docker run -it --rm alpine:3.24 sh
/ # cat /etc/os-release | head -n 2
NAME="Alpine Linux"
ID=alpine
/ # ps
PID USER TIME COMMAND
1 root 0:00 sh
9 root 0:00 ps
/ # exit
Look at the ps output. Inside the container, the shell is process 1, and only two processes exist. That’s a PID namespace at work. The first process in a new PID namespace gets PID 1, and the Linux system running it knows the same process by a different ID.
docker exec runs a command in a container that’s already running. Add -it and you get a shell inside web.
$ docker exec -it web bash
root@398423d33a7b:/# nginx -v
nginx version: nginx/1.30.6
root@398423d33a7b:/# ls /usr/share/nginx/html
50x.html index.html
root@398423d33a7b:/# exit
exit
What's next:
Try Docker Debug for seamless, persistent debugging tools in any container or image → docker debug web
Learn more at https://docs.docker.com/go/debug-cli/
Anything you change in there lasts only as long as that container. Step 9 shows why, and what to do about it.
Step 6. Write your first Dockerfile
A Dockerfile is a text file with the steps to build an image. Picture turning on a brand new computer for the first time. You’d install a base system, add the program you need and say what should start. A Dockerfile writes those steps down.
Make a folder for it and create a file named Dockerfile inside it.
$ mkdir ~/docker-demo/redis
$ cd ~/docker-demo/redis
FROM alpine:3.24
RUN apk add --no-cache redis
CMD ["redis-server"]
Three instructions build a Redis server, a small in-memory database.
FROM alpine:3.24starts from the Alpine Linux image. A version tag keeps the build the same next month.RUN apk add --no-cache redisinstalls Redis with Alpine’s package manager.--no-cachefetches the package index on the fly without storing it, so the image doesn’t carry it around.CMD ["redis-server"]sets the command a container runs when it starts.
Build it. -t my-redis names the image, and the . tells Docker to use the current folder, called the build context.
$ docker build -t my-redis .
...
#5 [2/2] RUN apk add --no-cache redis
#5 0.795 (1/1) Installing redis (8.8.0-r0)
#5 0.853 Executing redis-8.8.0-r0.pre-install
#5 0.977 Executing redis-8.8.0-r0.post-install
#5 0.979 Executing busybox-1.37.0-r31.trigger
#5 0.983 OK: 12.4 MiB in 17 packages
#5 DONE 1.1s
...
#6 naming to docker.io/library/my-redis:latest done
...
Run it and ask Redis if it’s alive.
$ docker run -d --name my-redis my-redis
38c72deae8db9a65b3387d0805ab8963668aced18aa41ac55d4c389c9fc88b26
$ docker exec my-redis redis-cli ping
PONG
Each instruction became a layer of the image. docker history lists them, newest first.
$ docker history my-redis
IMAGE CREATED CREATED BY SIZE COMMENT
fc6cf56cdfe4 2 seconds ago CMD ["redis-server"] 0B buildkit.dockerfile.v0
<missing> 2 seconds ago RUN /bin/sh -c apk add --no-cache redis # bu… 4.54MB buildkit.dockerfile.v0
<missing> 12 days ago CMD ["/bin/sh"] 0B buildkit.dockerfile.v0
<missing> 12 days ago ADD alpine-minirootfs-3.24.3-aarch64.tar.gz … 9.31MB buildkit.dockerfile.v0
The bottom two lines are the Alpine base, and the top two are yours. Layers are why Docker builds fast and why images share space, which Step 7 puts to work.
Step 7. Containerize a small Python web app
Now build an image for an app of your own. Visits is a tiny Flask page that shows which environment it runs in and, once it has a database, how many visits it has saved. My Django vs. Flask comparison explains Flask if it’s new to you. Create the folder and its files.
$ mkdir -p ~/docker-demo/visits/templates ~/docker-demo/visits/static
$ cd ~/docker-demo/visits
app.py is the whole app. It reads its settings from environment variables, which Step 8 uses. If MySQL can’t be reached, a try block catches the error and the page says so instead of crashing, the pattern from my Python exception handling guide.
import os
import platform
import socket
import pymysql
from flask import Flask, render_template
app = Flask(__name__)
def count_visit():
"""Save one visit in MySQL and return (total, status). Without DB_HOST there is no database."""
host = os.environ.get("DB_HOST")
if not host:
return None, "No database yet. Set DB_HOST to connect one."
try:
conn = pymysql.connect(
host=host,
user="root",
password=os.environ.get("DB_PASSWORD", ""),
database="visits",
connect_timeout=3,
)
except pymysql.MySQLError as exc:
return None, f"Can't reach {host}. {exc.args[-1]}"
with conn, conn.cursor() as cur:
cur.execute(
"CREATE TABLE IF NOT EXISTS visits ("
"id INT AUTO_INCREMENT PRIMARY KEY, "
"seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
)
cur.execute("INSERT INTO visits () VALUES ()")
conn.commit()
cur.execute("SELECT COUNT(*), VERSION() FROM visits")
total, version = cur.fetchone()
return total, f"MySQL {version} at {host}"
@app.route("/")
def home():
total, database = count_visit()
return render_template(
"index.html",
env=os.environ.get("APP_ENV", "local"),
container=socket.gethostname(),
python=platform.python_version(),
total=total,
database=database,
)
templates/index.html is the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Visits ({{ env }})</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<main class="card">
<header>
<h1>Visits</h1>
<span class="badge badge-{{ env }}">{{ env }}</span>
</header>
{% if total is not none %}
<p class="total">{{ total }}</p>
<p class="label">{{ "visit" if total == 1 else "visits" }} saved in MySQL</p>
{% else %}
<p class="total total-empty">0</p>
<p class="label">visits saved, no database connected</p>
{% endif %}
<dl>
<dt>Container</dt><dd><code>{{ container }}</code></dd>
<dt>Python</dt><dd>{{ python }}</dd>
<dt>Database</dt><dd>{{ database }}</dd>
</dl>
</main>
</body>
</html>
static/style.css gives it a dark look.
:root { color-scheme: dark; --line: #262a34; --muted: #9098a8; }
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0e1014; color: #e9ebf0; font: 16px/1.5 system-ui, sans-serif; }
.card { width: min(420px, calc(100vw - 32px)); padding: 28px; background: #161920; border: 1px solid var(--line); border-radius: 14px; }
header { display: flex; align-items: center; justify-content: space-between; }
h1 { margin: 0; font-size: 20px; }
.badge { padding: 3px 12px; border: 1px solid; border-radius: 999px; color: var(--muted); font-size: 13px; font-weight: 600; }
.badge-staging { color: #f2b65c; }
.badge-production { color: #62d69a; }
.total { margin: 28px 0 0; font-size: 64px; font-weight: 700; line-height: 1; }
.total-empty, .label, dt { color: var(--muted); }
.label { margin: 8px 0 24px; }
dl { display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; margin: 0; padding-top: 20px; border-top: 1px solid var(--line); font-size: 14px; }
dd { margin: 0; overflow-wrap: anywhere; }
code { font: 13px ui-monospace, Menlo, monospace; }
requirements.txt pins the three packages. pymysql[rsa] adds the extra package that PyMySQL needs to log in to MySQL 8, which you’ll do in Step 10.
flask==3.1.3
gunicorn==26.2.0
pymysql[rsa]==1.2.3
.dockerignore keeps junk out of the build context, the same way .gitignore keeps it out of Git.
__pycache__/
*.pyc
.venv/
.git/
And the Dockerfile, with a comment on every step.
# Start from a small official Python image.
FROM python:3.15-slim
# Create a normal user, so the app doesn't run as root.
RUN useradd --create-home app
# Every command after this runs inside /app.
WORKDIR /app
# Install the packages first. Docker caches this layer until requirements.txt changes.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Then copy the app code.
COPY . .
USER app
EXPOSE 8000
# 0.0.0.0 accepts connections from outside the container.
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
EXPOSE doesn’t publish anything. It only documents the port, and you still need -p when you run it. Build the image and run a container from it.
$ docker build -t visits .
...
#6 [2/6] RUN useradd --create-home app
#6 DONE 0.1s
#7 [3/6] WORKDIR /app
#7 DONE 0.0s
#8 [4/6] COPY requirements.txt .
#8 DONE 0.0s
#9 [5/6] RUN pip install --no-cache-dir -r requirements.txt
...
#9 5.029 Successfully installed blinker-1.9.0 cffi-2.1.1 click-8.5.0 cryptography-50.0.2 flask-3.1.3 gunicorn-26.2.0 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.4 pycparser-3.12 pymysql-1.2.3 werkzeug-3.1.9
...
#9 DONE 5.1s
#10 [6/6] COPY . .
#10 DONE 0.0s
...
#11 naming to docker.io/library/visits:latest done
...
The pip install step took 5.1 seconds, by far the slowest step. Now run the image.
$ docker run -d -p 8001:8000 --name visits visits
ebfd99ec60ac4135105d9f82702887cd013c85bc58e94b99fbc3f25012e10491
$ curl -s http://localhost:8001 | grep "<title>"
<title>Visits (local)</title>
$ docker images visits
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
visits:latest da6bc44f3390 259MB 56.7MB U
Open http://localhost:8001 and you’ll see the page with a local badge and no database yet.
Why copy requirements.txt before the code?
Docker caches every layer and reuses it until something it depends on changes. Packages change rarely and code changes all the time, so the Dockerfile installs packages first and copies the code last. Change a file and build again.
$ echo "# a small change" >> app.py
$ docker build -t visits .
...
#6 [3/6] WORKDIR /app
#6 CACHED
#7 [4/6] COPY requirements.txt .
#7 CACHED
#8 [2/6] RUN useradd --create-home app
#8 CACHED
#9 [5/6] RUN pip install --no-cache-dir -r requirements.txt
#9 CACHED
#10 [6/6] COPY . .
#10 DONE 0.0s
...
The pip install layer came straight from the cache, and only COPY . . ran again. Put COPY . . first and every one-line code change reinstalls every package. Enjoy watching pip download the same files again, every build, forever.
Docker Desktop shows the same layers. Click Images, then visits, and it lists each layer with its size. Rows 0 to 8 come from the Python base image, and rows 9 to 13 are your Dockerfile’s first five steps.

Why does the app listen on 0.0.0.0?
Inside a container, 127.0.0.1 means the container itself. A server bound there only answers calls from inside its own container, and Docker’s port forwarding arrives from outside it. Here’s the same image with Gunicorn bound to 127.0.0.1 instead.
$ docker run -d -p 8004:8000 --name visits-local visits gunicorn --bind 127.0.0.1:8000 app:app
0aae7f6916c47e56fbe13e64f3d4264097bbfa83dbcf01b214934c3a48900396
$ curl -sS http://localhost:8004
curl: (56) Recv failure: Connection reset by peer
$ docker rm -f visits-local
visits-local
The container runs fine and refuses every visitor. 0.0.0.0 means “accept connections on every network interface”, which is what the Dockerfile’s CMD uses.
What is the difference between CMD and ENTRYPOINT?
That last example also replaced the image’s CMD. Anything you type after the image name in docker run replaces CMD, so the same image can run something else entirely.
$ docker run --rm visits python --version
Python 3.15.2
ENTRYPOINT sets a fixed program, and CMD becomes its default arguments. A tiny image in ~/docker-demo/greet shows the difference.
FROM alpine:3.24
ENTRYPOINT ["echo", "Hello,"]
CMD ["world"]
$ docker build -t greet .
...
#5 naming to docker.io/library/greet:latest done
...
$ docker run --rm greet
Hello, world
$ docker run --rm greet Docker
Hello, Docker
$ docker run --rm --entrypoint date greet
Tue Nov 3 17:22:38 UTC 2026
| You type | Docker runs |
|---|---|
docker run --rm greet |
echo Hello, world, the ENTRYPOINT plus the default CMD |
docker run --rm greet Docker |
echo Hello, Docker, because your argument replaced CMD |
docker run --rm --entrypoint date greet |
date, because --entrypoint replaced the ENTRYPOINT |
You’ll read in older tutorials that ENTRYPOINT can’t be overridden. It can, with --entrypoint, and the Dockerfile reference says so. Arguments after the image name are appended to an exec-form ENTRYPOINT and replace CMD.
Remove the test container before the next step.
$ docker rm -f visits
visits
Step 8. Configure the app with environment variables
Settings that change between environments, like which database to use or what to call the environment, don’t belong in the code. If they live in the code, changing one means editing and rebuilding. Move them into environment variables and the same image runs anywhere.
app.py reads APP_ENV and shows it as a badge. -e sets it when the container starts. Run two containers from one image, one as staging and one as production.
$ docker run -d -p 8001:8000 -e APP_ENV=staging --name visits-staging visits
c5e7321eb6251d9d05ebf67ff6451eae8817549d8e3780d0c36086e24375378f
$ docker run -d -p 8002:8000 -e APP_ENV=production --name visits-production visits
58a901d9661d6b695262871b0e22e1515aeddd25bd42d6a37b1ee23dcfb6a6da
$ curl -s http://localhost:8001 | grep "<title>"; curl -s http://localhost:8002 | grep "<title>"
<title>Visits (staging)</title>
<title>Visits (production)</title>

One image, two containers, two settings. That’s the same idea behind my staging and production setup, just smaller.
docker inspect shows the variables a container was started with.
$ docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' visits-staging
APP_ENV=staging
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LANG=C.UTF-8
PYTHON_VERSION=3.15.2
PYTHON_SHA256=8b5536d280142ecf6cdfe15d12a21ba1c65e300bbf7b28a8d0cdb849575797de
APP_ENV is yours. The rest came from the Python base image. Anyone who can run docker inspect on your machine can read these, so treat every variable as visible.
Docker Desktop shows the same list. Click a container, open its Inspect tab and pick Env to jump to it.

Step 9. Keep data with volumes and bind mounts
An image is read-only. When a container starts, Docker adds a thin writable layer on top, and everything the container writes goes there. Delete the container and that layer goes with it.
What is copy-on-write?
When a container changes a file that came from the image, Docker first copies the file up into the writable layer and changes the copy. The image itself never changes. This is called copy-on-write. Edit nginx’s page inside web, then ask Docker what changed.
$ docker exec web sh -c 'echo "<!-- edited inside the container -->" >> /usr/share/nginx/html/index.html'
$ docker diff web
C /etc
C /etc/nginx
C /etc/nginx/conf.d
C /etc/nginx/conf.d/default.conf
C /usr
C /usr/share
C /usr/share/nginx
C /usr/share/nginx/html
C /usr/share/nginx/html/index.html
C /root
A /root/.bash_history
C /run
A /run/nginx.pid
C /var
C /var/cache
C /var/cache/nginx
A /var/cache/nginx/uwsgi_temp
A /var/cache/nginx/client_temp
A /var/cache/nginx/fastcgi_temp
A /var/cache/nginx/proxy_temp
A /var/cache/nginx/scgi_temp
C means changed and A means added. Your edit is the C on index.html. Most of the rest are files nginx created or changed while it started and ran, plus /root/.bash_history from your shell in Step 5. All of it disappears with the container.
For a database that’s a disaster waiting to happen. Volumes fix it.
How do you keep a database’s data with a volume?
A volume is storage that Docker manages outside any container, so it survives when containers come and go. Create one and start MySQL with it. The official MySQL image requires MYSQL_ROOT_PASSWORD, and MYSQL_DATABASE creates a database on the first start.
$ docker volume create visits-data
visits-data
$ docker run -d --name mysql-db -e MYSQL_ROOT_PASSWORD=db_pass123 -e MYSQL_DATABASE=visits -v visits-data:/var/lib/mysql mysql:8.4
...
bcfe2117ea4dfc840f0fdc85072fd59123c9ded3a2f75a468533e6ebd3104086
-v visits-data:/var/lib/mysql mounts the volume where MySQL keeps its data files. If you skip docker volume create, Docker creates the volume for you on the first run.
MySQL needs a little while on its first start, because it sets up its data files. Wait for the line with port 3306.
$ docker logs mysql-db 2>&1 | grep "ready for connections"
2026-11-03T17:23:05.896137Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
2026-11-03T17:23:05.896206Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.13' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server - GPL.
2026-11-03T17:23:08.002516Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2026-11-03T17:23:08.002582Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.13' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
The first ready line, with port 0, is a short setup run that the image’s entrypoint script does with networking switched off. The line with port 3306 is the real server. Now save a row, then crash the database on purpose.
$ docker exec mysql-db mysql -uroot -pdb_pass123 -e "CREATE TABLE visits.notes (body TEXT); INSERT INTO visits.notes VALUES ('I was here before the crash');"
mysql: [Warning] Using a password on the command line interface can be insecure.
$ docker rm -f mysql-db
mysql-db
The warning is MySQL’s, and it’s fine for a local demo. Start a new container with the same command and the same volume, and look for the row.
$ docker run -d --name mysql-db -e MYSQL_ROOT_PASSWORD=db_pass123 -e MYSQL_DATABASE=visits -v visits-data:/var/lib/mysql mysql:8.4
344e42d2b07eb0e6b88ac7ee0bd06a0afcfe1946c7d8546651635eb8d689f472
$ docker exec mysql-db mysql -uroot -pdb_pass123 -e 'SELECT * FROM visits.notes'
mysql: [Warning] Using a password on the command line interface can be insecure.
body
I was here before the crash
The container is brand new and the data is still there. That’s the whole point of a volume.
$ docker volume ls --filter name=visits
DRIVER VOLUME NAME
local visits-data
$ docker volume inspect visits-data
[
{
"CreatedAt": "2026-11-03T17:22:39Z",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/visits-data/_data",
"Name": "visits-data",
"Options": null,
"Scope": "local"
}
]
That Mountpoint lives inside Docker Desktop’s VM, not on your Mac, so don’t go looking for it in Finder.

What is a bind mount?
A bind mount mounts a folder from your machine into a container by its path. Change a file on your machine and the container sees it at once, which is great for code you’re editing. Make a site folder with one page and serve it with nginx.
$ mkdir ~/docker-demo/site
$ cd ~/docker-demo
<h1>Hello from a folder on the host</h1>
$ docker run -d -p 8085:80 --name site -v "$(pwd)/site:/usr/share/nginx/html" nginx:1.30
2e575b9d81d485a75b67d38f01ea46de1522ff026cbedf50c2b95fa4d71e8b01
$ curl -s http://localhost:8085
<h1>Hello from a folder on the host</h1>
$ echo '<h1>Edited on the host, no rebuild needed</h1>' > site/index.html
$ curl -s http://localhost:8085
<h1>Edited on the host, no rebuild needed</h1>
No rebuild and no restart. The container read the edited file straight from your folder. On a Mac, Docker Desktop shares only /Users, /Volumes, /private, /tmp and /var/folders by default, so keep bind-mounted folders under your home folder.
| Volume | Bind mount | |
|---|---|---|
| Where the data lives | In storage Docker manages | In a folder you pick on your machine |
| Created by | docker volume create, or Docker on first use |
You, before you run the container |
| Best for | Databases and anything that must outlast containers | Code and config you edit while the container runs |
Step 10. Connect the app to MySQL with a network
Docker creates three networks when you install it.
$ docker network ls --filter type=builtin
NETWORK ID NAME DRIVER SCOPE
ab41852b1dd2 bridge bridge local
3cd16617dc7b host host local
f5eac9594443 none null local
bridge is the default. Every container you’ve run so far joined it, which is how web got its 172.17 address in Step 3. none gives a container no network at all.
$ docker run --rm --network none alpine:3.24 ping -c 1 -W 2 1.1.1.1
PING 1.1.1.1 (1.1.1.1): 56 data bytes
ping: sendto: Network unreachable
host drops the network wall between the container and the machine running it. On Docker Desktop it’s off by default and needs a Docker sign-in to turn on, and this tutorial doesn’t need it.
Why can’t containers find each other by name?
The app needs to reach MySQL by a name like mysql-db. On the default bridge network, that name means nothing.
$ docker run --rm alpine:3.24 ping -c 1 mysql-db
ping: bad address 'mysql-db'
Containers on the default bridge can’t resolve each other by name. A network you create yourself can. Create one, then start MySQL again on it, with the same volume.
$ docker network create visits-net
6284a15ded8e04af15488f9051601232d04735f69feefba229ad8b2134054299
$ docker rm -f mysql-db
mysql-db
$ docker run -d --name mysql-db --network visits-net -e MYSQL_ROOT_PASSWORD=db_pass123 -e MYSQL_DATABASE=visits -v visits-data:/var/lib/mysql mysql:8.4
8cec5ca7b526ae00dafb2b2f5e10ed952f44a89cde21a62fd9db8d9e8d36cbfc
$ docker run --rm --network visits-net alpine:3.24 ping -c 1 mysql-db
PING mysql-db (172.21.0.2): 56 data bytes
64 bytes from 172.21.0.2: seq=0 ttl=64 time=0.105 ms
--- mysql-db ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.105/0.105/0.105 ms
Now the name resolves. Start the app on the same network and tell it where the database is.
$ docker run -d -p 8003:8000 --name visits-app --network visits-net -e APP_ENV=staging -e DB_HOST=mysql-db -e DB_PASSWORD=db_pass123 visits
82d3ff690e23077b0cac60fad9cfcae07d13a63f3923a3f7087f07cf90d5a0fe
$ curl -s http://localhost:8003 | grep -E "class=\"total\"|MySQL"
<p class="total">1</p>
<p class="label">visit saved in MySQL</p>
<dt>Database</dt><dd>MySQL 8.4.13 at mysql-db</dd>
$ curl -s http://localhost:8003 | grep -E "class=\"total\"|MySQL"
<p class="total">2</p>
<p class="label">visits saved in MySQL</p>
<dt>Database</dt><dd>MySQL 8.4.13 at mysql-db</dd>
Each visit adds a row, and the count goes up. Open http://localhost:8003 and you’ll see the page from the top of this post, with a staging badge and the MySQL version.
The magic behind the name is a DNS server built into Docker. Containers on a network you create use Docker’s embedded DNS server at 127.0.0.11, and you can see it in the app’s own config.
$ docker exec visits-app cat /etc/resolv.conf
# Generated by Docker Engine.
# This file can be edited; Docker Engine will not make further changes once it
# has been modified.
nameserver 127.0.0.11
options ndots:0
# Based on host file: '/etc/resolv.conf' (internal resolver)
# ExtServers: [host(192.168.65.7)]
# Overrides: []
# Option ndots from: internal
$ docker network inspect -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}' visits-net
visits-app 172.21.0.3/16
mysql-db 172.21.0.2/16
What about –link?
Older tutorials connect containers with --link. Docker’s own docs call it legacy, and Engine 29 no longer adds the environment variables it used to. Use it now and Docker tells you what it thinks.
$ docker run --rm --link web alpine:3.24 true
WARNING: Links on the default bridge network are deprecated and will be removed in a future release. Use a custom network instead.
Docker deprecating your tutorial in real time is a strong hint. Use a network you create.
Step 11. Run the whole stack with Docker Compose
Steps 9 and 10 took a volume, a network and two long docker run commands. Docker Compose puts all of that in one YAML file, a plain text format for settings, and starts it with one command. Create compose.yaml in ~/docker-demo/visits.
services:
web:
build: .
ports:
- "8000:8000"
environment:
APP_ENV: production
DB_HOST: db
DB_PASSWORD: db_pass123
depends_on:
db:
condition: service_healthy
db:
image: mysql:8.4
environment:
MYSQL_ROOT_PASSWORD: db_pass123
MYSQL_DATABASE: visits
volumes:
- db-data:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"]
interval: 5s
retries: 20
volumes:
db-data:
Two services, web and db, and one volume.
build: .builds the image from the Dockerfile in this folder.environmentsets the same variables you passed with-e. The app reaches MySQL atdb, the service name.depends_onwithcondition: service_healthymakes Compose wait for the database’s health check to pass before it startsweb.healthcheckrunsmysqladmin pingevery 5 seconds to ask MySQL if it’s up.- There’s no
version:line at the top. Older files have one, and it’s obsolete.
The passwords sit in the file here because it’s a local demo. My Django in Docker guide moves them into an env file, which is what a real project needs.
Bring it all up. --build builds the web image first, and -d runs everything in the background, like docker run -d.
$ docker compose up -d --build
...
Image visits-web Built
Network visits_default Creating
Volume visits_db-data Creating
Network visits_default Creating
Volume visits_db-data Creating
Volume visits_db-data Created
Volume visits_db-data Created
Network visits_default Created
Network visits_default Created
Container visits-db-1 Creating
Container visits-db-1 Created
Container visits-web-1 Creating
Container visits-web-1 Created
Container visits-db-1 Starting
Container visits-db-1 Started
Container visits-db-1 Waiting
Container visits-db-1 Healthy
Container visits-web-1 Starting
Container visits-web-1 Started
The web image built first. Then Compose created the network and the volume, started db, waited for it to report healthy, and only then started web.
$ docker compose ps
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
visits-db-1 mysql:8.4 "docker-entrypoint.s…" db 8 seconds ago Up 7 seconds (healthy) 3306/tcp, 33060/tcp
visits-web-1 visits-web "gunicorn --bind 0.0…" web 8 seconds ago Up 2 seconds 0.0.0.0:8000->8000/tcp, [::]:8000->8000/tcp
$ curl -s http://localhost:8000 | grep -E "class=\"total\"|MySQL"
<p class="total">1</p>
<p class="label">visit saved in MySQL</p>
<dt>Database</dt><dd>MySQL 8.4.13 at db</dd>
Compose made a network for the two services, so no docker network create and no --link. It also named the project after the folder, visits, and put that name in front of everything it created. That’s why you see visits-web-1, visits-db-1, visits_db-data and visits_default.
$ docker compose logs web
web-1 | [2026-11-03 17:23:26 +0000] [1] [INFO] Starting gunicorn 26.2.0
web-1 | [2026-11-03 17:23:26 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
web-1 | [2026-11-03 17:23:26 +0000] [1] [INFO] Using worker: sync
web-1 | [2026-11-03 17:23:26 +0000] [7] [INFO] Booting worker with pid: 7
web-1 | [2026-11-03 17:23:26 +0000] [1] [INFO] Control socket listening at /home/app/.gunicorn/gunicorn.ctl
Docker Desktop groups the two Compose containers under the project name visits and lists them by their short names, web-1 and db-1.

docker compose down removes the containers and the network but keeps the volume. Bring it back up and the count carries on.
$ docker compose down
Container visits-web-1 Stopping
Container visits-web-1 Stopped
Container visits-web-1 Removing
Container visits-web-1 Removed
Container visits-db-1 Stopping
Container visits-db-1 Stopped
Container visits-db-1 Removing
Container visits-db-1 Removed
Network visits_default Removing
Network visits_default Removed
$ docker compose up -d
...
Container visits-web-1 Starting
Container visits-web-1 Started
$ curl -s http://localhost:8000 | grep -E "class=\"total\"|MySQL"
<p class="total">2</p>
<p class="label">visits saved in MySQL</p>
<dt>Database</dt><dd>MySQL 8.4.13 at db</dd>
$ docker volume ls --filter name=visits
DRIVER VOLUME NAME
local visits-data
local visits_db-data
down -v removes the volume too, so use it only when you want a clean slate.
$ docker compose down -v
Container visits-web-1 Stopping
Container visits-web-1 Stopped
Container visits-web-1 Removing
Container visits-web-1 Removed
Container visits-db-1 Stopping
Container visits-db-1 Stopped
Container visits-db-1 Removing
Container visits-db-1 Removed
Network visits_default Removing
Volume visits_db-data Removing
Volume visits_db-data Removed
Network visits_default Removed
Older tutorials start their Compose files with a version: line. Here’s the same file with version: "3.8" added at the top, in a folder named old-compose. docker compose config --quiet checks a file without starting anything.
$ docker compose config --quiet
time="2026-11-03T09:23:39-08:00" level=warning msg="/Users/you/docker-demo/old-compose/compose.yaml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
Step 12. Share your image through a registry
So far every image you built lives only on your machine. A registry stores images so other machines can pull them. Docker Hub is the public one. You can also run a private registry, and the official registry image is the quickest way to try one.
The registry listens on port 5000 inside its container. On my Mac, port 5000 was already taken by ControlCenter, a macOS system process, so mapping it there fails.
$ docker run -d -p 5000:5000 --name registry-5000 registry:3
...
9b2841691dac357e71da58d049674e2afdaba60a53dc0cc2cc296ba11f4c2a28
docker: Error response from daemon: ports are not available: exposing port TCP 0.0.0.0:5000 -> 127.0.0.1:0: listen tcp 0.0.0.0:5000: bind: address already in use
Run 'docker run --help' for more information
$ docker rm registry-5000
registry-5000
Any free port works. Use 5001 on your machine.
$ docker run -d -p 5001:5000 --name registry registry:3
f594b6693d860cf086bd5ea2790f6bf45d2b9f70a3f4f696b37e6ef27186b1bb
To push an image to a registry, tag it with the registry’s address first. The tag tells docker push where the image goes.
$ docker image tag visits localhost:5001/visits:1.0
$ docker push localhost:5001/visits:1.0
...
1f00f9c86268: Pushed
2b70e040f7d1: Pushed
1.0: digest: sha256:263232ddedf47f1b227b95701e2da83345d7bb3972bac684f7f6373a0fffb137 size: 856
$ curl -s http://localhost:5001/v2/_catalog
{"repositories":["visits"]}
The registry now holds visits. Remove the local tag and pull it back, the way another machine would.
$ docker rmi localhost:5001/visits:1.0
Untagged: localhost:5001/visits:1.0
$ docker pull localhost:5001/visits:1.0
1.0: Pulling from visits
Digest: sha256:263232ddedf47f1b227b95701e2da83345d7bb3972bac684f7f6373a0fffb137
Status: Downloaded newer image for localhost:5001/visits:1.0
localhost:5001/visits:1.0
Docker Desktop’s Images view shows both tags pointing at one image.

Pushing to Docker Hub works the same way with your Docker Hub username in the tag. Swap USERNAME for yours.
$ docker login
$ docker image tag visits USERNAME/visits:1.0
$ docker push USERNAME/visits:1.0
A private registry at a company works the same way, with its address in the tag and a docker login to that address first.
How do you limit a container’s CPU and memory?
A container shares the machine’s CPU and memory with everything else, so one busy container can starve the rest. --cpus and --memory set a ceiling. This container runs an endless loop with a limit of half a CPU and 100 MB of memory.
$ docker run -d --name busy --cpus=0.5 --memory=100m alpine:3.24 sh -c 'while true; do :; done'
936ee8130897b24b25134ef4cdd29de4c06b07cbacfe165b7b2c415ee5a481f3
$ docker stats --no-stream busy
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
936ee8130897 busy 49.88% 632KiB / 100MiB 0.62% 872B / 126B 0B / 0B 1
$ docker rm -f busy
busy
The loop wants all the CPU it can get, and it gets almost exactly 50%.
Note what that 50% means. --cpus=0.5 is half of one CPU, not half of your machine. On a host with two CPUs, --cpus="1.5" caps a container at one and a half CPUs. --memory takes values like 100m, and the smallest it accepts is 6m.
Docker Desktop’s Stats tab draws the same cap over time. Click the container, then Stats.

Which Docker commands will you use every day?
Keep these eleven handy. They cover most of what you’ll type on a normal day.
| Command | What it does |
|---|---|
docker run -d -p 8080:80 --name web nginx:1.30 |
Starts a container in the background with a port mapping |
docker ps, docker ps -a |
Lists running containers, or all of them |
docker logs -f web |
Follows a container’s output |
docker exec -it web bash |
Opens a shell in a running container |
docker stop web, docker start web |
Stops or starts a container |
docker rm web, docker rm -f web |
Removes a stopped container, or stops and removes |
docker images, docker pull nginx:1.30 |
Lists or downloads images |
docker rmi nginx:1.30 |
Removes an image tag |
docker build -t visits . |
Builds an image from the Dockerfile here |
docker volume ls, docker network ls |
Lists volumes or networks |
docker compose up -d, docker compose down |
Starts or stops everything in compose.yaml |
How do you fix common beginner Docker errors?
Each fix below starts from the exact message Docker prints, so you can match it to what’s on your screen.
Why does Docker say the port is already allocated?
Another container already maps that host port. Use a different left-hand port, or stop the other container. Docker still creates the failed container, so docker rm it before you try again.
$ docker run -d -p 8080:80 --name web2 nginx:1.30
c13a7e34d1d3f7177f8c36d257785e75c91951d475246124e4eedf36a6e00915
docker: Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint web2 (4f88d97bd510d2a6ebe54b3c2df18bdc05149015cfcf9701fbc9424654e34eaf): Bind for 0.0.0.0:8080 failed: port is already allocated
Run 'docker run --help' for more information
If Docker says address already in use instead, a program outside Docker holds the port, like ControlCenter on port 5000 on my Mac. Pick another port.
Why does Docker say the container name is already in use?
Names are unique, and stopped containers keep theirs. Remove the old container or pick another name.
$ docker run -d --name web nginx:1.30
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "398423d33a7bd4515231b7a34bafa5bc66251682a2cda01fd13c6600970ff900". You have to remove (or rename) that container to be able to reuse that name.
Run 'docker run --help' for more information
Why does Docker say it failed to connect to the Docker API?
Docker Desktop isn’t running, so the docker command has nothing to talk to. The error starts with failed to connect to the docker API and ends with check if the path is correct and if the daemon is running. Open Docker Desktop and wait until the engine is running.
Why does the page not load when the container is running?
Two usual suspects. Either you forgot -p, or the app inside listens on 127.0.0.1. Step 7 shows the second one failing with Connection reset by peer. Bind the app to 0.0.0.0.
Why does my container exit right away?
Its main process finished. An Alpine container with no command runs sh, and a shell with no terminal has nothing to do.
$ docker run -d --name quick alpine:3.24
c179b69f9a60d8d8b6b0d57f5494c7c2ed2ca0704dfb4ed5f20ad0de2a2287f3
$ docker ps -a --filter name=quick
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c179b69f9a60 alpine:3.24 "/bin/sh" 2 seconds ago Exited (0) 2 seconds ago quick
Give it a long-running command, or use -it if you want the shell.
Why does Compose say the version attribute is obsolete?
Your compose.yaml starts with a version: line from an older tutorial. Delete the line. Compose ignores it anyway.
Why does Docker warn that links are deprecated?
The command uses --link. Put both containers on a network you create, as in Step 10, and drop the flag.
What else do beginners ask about Docker?
Is Docker free?
Docker Engine, the part that runs containers, is free and open source under the Apache License 2.0. Docker Desktop is free for personal use, education, non-commercial open source projects and small businesses, which Docker defines as fewer than 250 employees and less than $10 million in annual revenue. Larger organizations need a paid Pro, Team or Business subscription.
Does Docker work on Apple Silicon Macs?
Yes. Every step in this tutorial ran on an M2 Max. Docker pulled the arm64 build of each image, which the hello-world output in Step 1 shows as (arm64v8), and it printed no platform warnings along the way.
Does Docker work on Windows?
Yes. Docker Desktop for Windows runs Linux containers through the WSL 2 backend. I ran this tutorial on a Mac, so on Windows type the commands into a WSL terminal, which gives you the same Linux shell they were written for. My WSL guide covers setting WSL up.
What comes after this Docker tutorial for beginners?
You’ve run, built, configured, connected, composed and shared containers. The best way to practice now is with your own code, so pick something from my Python project ideas and write a Dockerfile for it. After that comes a real app with real secrets. My Django in Docker guide runs Django with PostgreSQL and Gunicorn, with staging and production on one machine. To build your images automatically on every push, my GitHub workflows tutorial runs tests and builds in CI, and my self-hosted runner guide runs those jobs on a machine you own.
Running containers across many machines is called orchestration. Kubernetes is the best-known system for it, and Docker has its own Swarm mode, where manager and worker nodes share the work. Both build on the same images, containers, volumes and networks you used here.
Which part of Docker tripped you up first, the ports, the volumes or the networks?