Lesson 47 showed you what a container is. This lesson is the one where you build one. A small app, a short Dockerfile, and four commands: build it, run it, tag it, push it. By the end the app runs on your machine from an image, and the same image can run on any other machine. That is the whole deal, and you will have done it yourself.
Difficulty: Basic · Know this first: Lesson 47 — Containers and Docker
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with two files on a laptop. Add one box at a time until the app answers hello from a container.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the build, the push, and the pull change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: the size of the image and the warmth of the cache decide how fast the trip goes.
The base is the bottom layer everything else stacks on. A slim base is about 5 to 50 MB. A full operating system base is 500 MB or more.
One layer per Dockerfile line that changes the files. More layers mean more chances for the cache to miss, and each layer adds 20 MB in this model.
Share of layers the build reuses instead of rebuilding. A reused layer costs about 1 min in this model. A rebuilt layer costs about 12 min.
Try this: (1) Set base to 1000, layers to 20, cache to 0. The build is about 240 min, the pull about 117 min, the push about 70 min, and the total is about 430 min. (2) Set base to 5, layers to 3, cache to 100. The build is about 3 min, the pull about 5 min, the push about 3 min, and the total is about 14 min. Same app. Only the image changed.
Three questions. No score is saved anywhere — this is just you against the material.
Here is the Dockerfile from this lesson, ready to edit. Change it, then run the check. The check looks for the five lines a working first Dockerfile needs: a base image, a working folder, a copy, a build step, and a start command.
Try breaking it on purpose: delete the WORKDIR line, or change CMD to a plain string. Run the check and watch it fail. Then press Reset and try a change that keeps it passing, like adding an ENV line.
Expected output when it passes: The Dockerfile has a base, a folder, a copy, a build step, and a start command. This file would build.
I take the same trip four times here. First I learn the five moves: build, tag, push, pull, run. Then I learn what each move costs. Then I learn to read the log when a move fails. Last I run it for the world.
Definition: A container is a process that runs in its own box, with its own files, network, and process list. An image is the read only stack of layers the container is made from. A Dockerfile is the text file that says how to build the image. The registry is the shelf images wait on. Docker build makes the image. Docker run starts the container.
Types:
Uses: I use this for one small app on my own machine. I build it, I run it, I stop it, I remove it. Try it now: build the hello-docker image from the Try it box, run it, and curl it. Then stop it and remove it. Practice this in the Docker labs.
Dimensions: At low traffic everything is nearly free. What breaks first is the name: a typo in the tag, a Dockerfile in the wrong folder, a port already in use on the host. It costs one careful read of the error, which always names the thing it could not find.
Definition: Every instruction that changes the files adds one layer. Docker reuses a layer when the instruction and its inputs have not changed, and rebuilds it when they have. The order of the Dockerfile decides how much rebuilds when one file changes. Dependencies go first, because they change rarely. Code goes last, because it changes every day.
Types:
Uses: I use this when the build gets slow. I order the Dockerfile so the stable layers sit at the top, and I keep stray files out of the context with a .dockerignore file. Try it now: move the COPY of the code below the dependency install in the Try it box, and run the check. Then practice the ordering in the Docker labs.
Dimensions: As the app grows, the image grows, and the pull becomes the deploy. What breaks is the size: a 1.4 GB image means every host waits on the pull. It costs a slim base image and a multi-stage build, which is Lesson 145.
Definition: A tag is a pointer to one build. A version tag points at one build forever. The latest tag points at whatever was pushed last, so it moves. The digest points at the exact bytes, so it never moves. A registry can hold many tags for one image, and one image can live in many registries. Pushing the same layers twice costs nothing, because the registry keeps layers it already has.
Types:
Uses: I use version tags for every deploy, and I pin the digest in production. I log in once with docker login, and I watch for the unauthorized error, which means the login expired. Try it now: tag the image in the Try it box with 1.0.0 and with latest, and notice both rows share one image ID. Then practice tagging and pushing in the Docker labs.
docker login, and the commands around it. login is a one-line command with no flags here. It still deserves a careful read, because the push failure it fixes looks like a build failure.
docker login takes no image and no flags here. It asks for the registry username and password, and stores the login for the next push. Without a fresh login, a push fails with unauthorized, and the error is about the login, not the build.docker push uploads the image to the registry. The name must carry the registry path, like myname/hello-docker:1.0.0. Without the path, the push goes to the wrong place or fails outright.docker pull downloads the image from the registry. Without it run has to pull first, and a pull failure looks like a run failure.Flags you will meet next: docker login registry.example.com logs into a private registry instead of the default one.
Try it: run docker push with an expired login and read the error: unauthorized. Then run docker login and push again. The second push works. The build never changed. The login did.
Dimensions: At ten times the deploys, the tag is the contract. What breaks is a moving tag: latest in staging is not latest in prod, and a rollback pulls the wrong image. It costs version tags on every build and a digest pin where it matters.
Pin the digest, not just the tag. A tag moves. Latest today is not latest tomorrow, and a rebuild next month pulls a different base image than the one I tested. I pin the digest for anything that ships to production, so the image I tested is the image I deploy. I read the digest after the build and I write it down. A deploy that cannot name its digest is a deploy that cannot be reproduced.
Try it: run these commands and read the digest for your image.
# Run on a host with Docker. The digest is the part after the @.
docker build -t hello-docker:1.0.0 .
docker images --digests hello-docker
docker inspect hello-docker:1.0.0 --format "digest: {{.RepoDigests}}"
docker inspect --format, flag by flag. inspect prints everything. --format prints one thing. I use the flag when I already know what I am looking for.
--format prints one value from the JSON instead of the whole document, using a Go template. Without it inspect prints pages of JSON, and the one field I want is somewhere in the middle.{{.RepoDigests}} the list of digests the image was pushed under. The digest is the content hash, and it is the only name for an image that cannot move.{{.Id}} the path inside the JSON: the image ID. Two tags that share one ID are the same image under two names.Flags you will meet next: {{json .Config.Env}} prints a whole block as JSON, and {{.Id}} prints the image ID alone.
Try it: run docker inspect with no --format and pipe it to wc -l, then run it with --format '{{.State.Health.Status}}'. The first prints hundreds of lines. The second prints one word: healthy, unhealthy, or starting.
docker images, flag by flag. Images are the inventory. The flags decide which columns I see, and which images I see at all.
my-app filters the list to that repository. Without it I see every image on the host.--format "{{.Tag}} {{.Size}}" prints only the fields I name, using a Go template. Without it I get the full table, and the one column I want hides in the middle of it.--digests shows the digest column, the content hash of each image. Without it you see name, tag, ID, and size, but not the hash the registry uses to tell two builds apart.Flags you will meet next: -f dangling=true lists the untagged leftovers, and --format '{{.Repository}}:{{.Tag}} {{.Size}}' prints a one-line inventory.
Try it: run docker images, then docker images my-app --format '{{.Tag}} {{.ID}}'. The second run shows two columns and nothing else. The first run shows the whole table.
docker build, flag by flag. The build reads the Dockerfile and stacks the layers. The flags name the image, pick the file, and pass values in.
-t names the image name:tag. Without it the image gets no name and no tag, and I cannot run it or push it by name.. the build context: the folder Docker may copy files from. It is a path, not a flag, and it is required. A stray 2 GB file in that folder gets sent to the daemon on every build.Flags you will meet next: --no-cache rebuilds every layer, and --platform linux/amd64 builds for a different CPU than the one you sit on.
Try it: build the same Dockerfile twice, once with -t app:1.0.0 and once with no -t at all. The first one you can run by name. The second one shows as <none>, and you cannot run it without its ID.
Expected: the images line shows a digest like sha256: and the inspect line shows the same digest. If there is no digest, the image was never pushed or the tag is local only, and I push it before I call it done.
Definition: At this level the image stops being a laptop artifact and becomes a pipeline product. The pipeline builds it, scans it, signs it, and pushes it to a registry close to the hosts. Old images are cleaned up on a schedule. A deploy names the image by digest, so the same bytes run in staging and in prod. And I rehearse the worst day: the registry is down, the pull fails, the deploy waits.
Types:
Uses: I use this when more than one team ships through the same registry, or when a bad image can take down a service other teams depend on. It is also how I review a setup I did not build: I ask where the image is built, who can push, and what happens when the registry is gone. Try it now: open any image you own and find its digest. If you cannot find it, that is the first gap to close.
Dimensions: At a hundred times the pulls, the registry is not the bottleneck, the blast radius is. What breaks is the single registry every deploy depends on, or the disk that filled up with old images. It costs mirrors, cleanup rules, and a rehearsed registry outage.
When the push fails, read the error, not the retry. A push that fails on an expired login is not fixed by pushing again. The error says unauthorized, and the fix is a fresh login. A push that fails on a missing repository needs the repository created first. I keep a short list of the three push failures I actually see, the error text for each, and the one command that fixes it. The list lives in the runbook, so the next person does not spend an hour on a two-minute fix.
Try it: check whether your login is still valid before you push.
# Run on a host with Docker. Check the login before the push, not after it fails. docker login docker push hello-docker:1.0.0 echo "push exit code: $?"
Shell redirects, piece by piece. The command is half the line. The redirects are the other half. They decide where the output goes and what happens when the command fails.
> file sends stdout to a file. Without it the output goes to the terminal and is gone when I scroll past it.2>/dev/null sends stderr to nowhere. Errors disappear. I use it only when I expect the error, like a cleanup command that may find nothing to clean. Hiding errors I do not expect is how a real failure goes unnoticed for a week.2>&1 sends stderr to the same place as stdout, so the log file holds both. Without it the log has the normal output and the errors are lost.& runs the command in the background and returns the prompt. The shell prints the job number and PID, and I save the PID when I need to stop it later.|| true turns a failing command into a success, so a script does not stop on it. I use it for cleanup steps that are allowed to find nothing.$? the exit code of the last command. 0 means it worked. Anything else means it failed, and the number sometimes says why.Flags you will meet next: >> appends instead of overwriting, and set -e stops a script on the first failure.
Try it: run a command that fails, once with 2>/dev/null and once without it. Without it the error prints. With it the error is gone, and only the exit code in $? says anything happened.
docker push, flag by flag. Push uploads the image to the registry. The name on the image is the address it goes to.
docker push uploads the image to the registry. The name must carry the registry path, like myname/hello-docker:1.0.0. Without the path, the push goes to the wrong place or fails outright.Flags you will meet next: docker push --all-tags pushes every tag of the image at once.
Try it: push an image, then pull it on the same machine with docker pull. The pull should be instant, because the layers are already there. Then push with an expired login and read the error before you fix it.
Expected: the login succeeds and the push prints the layers going up. If the login fails, the push would have failed too, and I fixed it a minute earlier.
Start with the smallest app that works, and grow it one command at a time. The full file below is the one this lesson builds. Do this: save it as Dockerfile next to a server.js that answers hello on port 3000 and a package.json that names the app, run docker build -t hello-docker:1.0.0 ., and watch each step. Expected output: the log shows one step per line, and the last line names the image hello-docker:1.0.0.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "dist/server.js"]
What the snippet means: the base is a slim Node image, the work happens in /app, the dependency files are copied first so their layer stays cached, the dependencies install, then the code is copied last so a code change rebuilds only the last layer. The port is declared, and the container starts the server.
Image versus container is the first split to keep. Do this: run docker images and docker ps side by side. Expected output: docker images lists the packed app, hello-docker:1.0.0. docker ps lists the running container, hello. Stop the container with docker stop hello and run docker ps again. Expected output: the container is gone from the list, and the image is still there in docker images. The image survives the container.
docker stop and docker rm, flag by flag. Stop ends the run. Remove deletes the container. They are two steps, and skipping the second one leaves a stopped container holding its name.
docker stop hello stops the running container by name. It sends TERM first, then waits, then kills. A container that ignores TERM takes the full wait before it dies.docker rm hello removes a stopped container. A running container cannot be removed until it is stopped. Without rm the stopped container keeps its name, and the next run with that name fails.Flags you will meet next: docker rm -f stops and removes in one step, and docker stop -t 5 waits five seconds before killing.
Try it: run a container with --name hello, stop it, and try to run it again with the same name. It fails. Remove it with docker rm hello, run it again, and it works. The name was the blocker, not the image.
docker ps, flag by flag. ps shows what is running. The flags decide whether the stopped ones show up, and which columns I read.
--filter "status=exited" shows only containers that match. Without it ps shows every running container, and the stopped one I am looking for is not in the list at all.--format "{{.Names}} {{.Status}}" prints only the fields I name, using a Go template. Without it I get the full table.Flags you will meet next: -a shows stopped containers too, and --format '{{.Names}} {{.Ports}}' prints names and ports only.
Try it: stop a container, then run docker ps. It is gone from the list. Run docker ps --filter status=exited and it appears. The container did not vanish. The default view just hides stopped ones.
Tagging is cheap, so tag with intent. Do this: run docker tag hello-docker:1.0.0 myname/hello-docker:1.0.0 and then docker images. Expected output: two rows share one image ID. Then run docker image inspect hello-docker:1.0.0 --format '{{.Id}}'. Expected output: one long ID starting with sha256. That ID is the digest of the image on your machine.
docker tag, flag by flag. A tag is a name, not a copy. Tagging is how one build gets three names: a version, a date, and latest.
docker tag adds a second name to an image that already exists. A tag is a pointer, not a copy, so retagging costs nothing. The first name is the image I have. The second name is the name I want it to have.Flags you will meet next: docker tag takes no flags. The work is in the two names, and the order matters: the image you have first, the name you want second.
Try it: tag one image three ways, then run docker images my-app --format '{{.Tag}} {{.ID}}'. All three rows share one ID. That shared ID is the proof that a tag costs nothing.
The push and the pull are the same trip in two directions. Do this: run docker login, then docker push myname/hello-docker:1.0.0. Expected output: each layer shows as Pushed or Layer already exists, and the last line shows the digest. Then run docker rmi myname/hello-docker:1.0.0 and docker pull myname/hello-docker:1.0.0. Expected output: the pull restores the image, layer by layer. Practice the full loop in the Docker labs.
docker pull, flag by flag. Pull downloads the image from the registry. It is the mirror of push, and the first step of every fresh deploy.
docker pull downloads the image from the registry. Without it run has to pull first, and a pull failure looks like a run failure.Flags you will meet next: docker pull --platform linux/amd64 pulls the image for one CPU type when the host could take another.
Try it: pull an image, then run docker images and check the size. Pull it again and watch it say up to date. The second pull moves nothing, because the layers are already on disk.
docker rmi, flag by flag. rmi removes images from the host. It is the cleanup command, and it refuses to remove an image a container still uses.
docker rmi removes an image from the host. It takes one or more names. An image that a container still uses cannot be removed until the container is gone.Flags you will meet next: docker rmi -f forces the removal, and docker image prune removes all unused images at once.
Try it: build two tags of one image, remove one with docker rmi, and list the images. The other tag is still there, because a tag is a pointer and removing one pointer does not delete the image.
At 10x the deploys, the shape holds and the numbers grow. At 100x, the design changes: the pipeline builds the image, a scan gate checks it, and the deploy names the digest. The image never stops being a stack of layers. It just gets more readers. Lesson 145 is where the image gets small, and Lesson 146 is where it gets safe.
A tag scheme that changes per release is a scheme nobody can follow. I use one scheme: the version, always three numbers, and the digest recorded next to it. Latest is a convenience for local work and never the thing production runs. I write a tiny script that tags the image three ways from one build: the version, the version with the date, and latest for local use. The script is the scheme, and the scheme is the same every release.
# Tag one build three ways. Run on a host with Docker.
docker build -t my-app:1.4.0 .
docker tag my-app:1.4.0 my-app:1.4.0-20261120
docker tag my-app:1.4.0 my-app:latest
docker images my-app --format "{{.Tag}} {{.ID}}"
Expected: three tags, all with the same image ID. If the IDs differ, the tags point at different builds and the scheme is already broken.
I tagged an image latest, pushed it, and deployed it. The next day I pushed a broken build with the same latest tag, and the deploy that ran that night pulled the broken image into staging. The staging app went down, and the team testing staging lost half a day. The registry did exactly what I asked. I asked it to move the tag.
Two things. First, every build gets a version tag, and latest is never used for a deploy. Second, I check the tag on the deploy line before I trust it, the way I check the version on a release note. Try it now: open any deploy you own and find the tag it pulls. If it says latest, pin a version before the next deploy.
Build a working image for a small web app and run it from the registry, not from your laptop. It must have a Dockerfile with a base image, a working folder, a copy step, a build step, and a start command. It passes when the image builds, the container runs, and curl answers hello from the pulled image.
docker run, flag by flag. I read the flags before I read the image name. The flags are the whole instruction. The image is just what runs.
-d runs the container in the background and prints its ID, then returns the prompt. Without it the terminal stays attached to the app, and closing the terminal stops the container.-p 3000:3000 publishes a container port on the host. The order is host port first, container port second. Without it the port stays private inside the container network, and nothing on the host can reach it.--name hello names the container. Without it Docker picks a random name, and every later command has to use the ID or that random name.Flags you will meet next: -e sets an environment variable, --restart unless-stopped brings the container back after a reboot, and -it gives you a terminal inside it.
Try it: run the container with -d and then without it. With -d the prompt comes back at once. Without it the logs fill the terminal until you stop it.
Success looks like this: the build log ends with the image name. docker images shows the version tag. The push ends with a digest line. The pull restores the image. Curl prints hello from the container that came from the registry. If curl fails, the container is the first thing to check with docker logs hello.
If the build fails, read the step it failed on. A missing file means the COPY path is wrong. If the push says unauthorized, the login expired. Run docker login again. If the container exits at once, read its logs before you rebuild. The logs name the missing file or the bad port.