Dockerizing a Node App
Package your service and everything it needs into one portable image
- explain the difference between an image and a container;
- write a correct
Dockerfilefor an Express app; - order instructions so the layer cache works for you, not against you;
- shrink and harden images with multi-stage builds;
- inject configuration through environment variables at run time;
- build, run, and map ports for a containerized app.
1. From "works on my machine" to a shipping container
You finished the intermediate courses: you can build an Express API with routing, middleware, JWT auth, validation, a SQL or MongoDB layer, and tests. It runs perfectly on your machine. Then a teammate clones it and it breaks -- their Node is version 16, they are missing an environment variable, a native module fails to compile, or a system library is a different version. The code is identical; the environment is not.
Analogy. Before standardized shipping containers, cargo was loaded loose, piece by piece, and every ship, crane and truck handled it differently. The steel container changed everything: pack goods once, and any ship or crane in the world moves that identical box without caring what is inside. A Docker image is that box for software. You package the app, its Node runtime, its dependencies and its files once; any host running Docker can run that identical box without caring how it was built.
Docker does this with OS-level virtualization. A container is an isolated process on the host's Linux kernel -- not a full virtual machine with its own kernel. That is why containers start in milliseconds and add almost no overhead, while still giving each app its own private filesystem, network view and process space.