Docker for Beginners: Containerizing Your First App
Docker lets you package an application with everything it needs to run — code, runtime, libraries, system tools — into a single image that behaves the same on your laptop, a teammate's machine, and production. This post walks through containerizing a simple Node.js app from scratch.
Why Containers?
Before containers, "it works on my machine" was a real problem: different Node versions, missing environment variables, OS-specific quirks. A container bundles the exact runtime and dependencies your app needs, so the same image runs identically everywhere Docker is installed.
Writing a Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
A few things worth noting:
node:20-alpineis a small base image — smaller images build and deploy faster.- Copying
package*.jsonbefore the rest of the code lets Docker cache thenpm cilayer, so dependency installs are skipped when only your source changes. EXPOSEis documentation — it doesn't actually publish the port; that happens atdocker run.
Building and Running
docker build -t my-app .
docker run -p 3000:3000 my-app
-p 3000:3000 maps port 3000 on your machine to port 3000 inside the container.
Using .dockerignore
Just like .gitignore, a .dockerignore file keeps unnecessary files out of the build context, which speeds up builds and avoids leaking local files like .env or node_modules into the image:
node_modules
.env
.git
npm-debug.log
Multi-Stage Builds
For compiled languages or frontend builds, multi-stage builds keep your final image small by discarding build tools once they've done their job:
FROM node:20-alpine AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY package*.json ./
RUN npm ci --production
CMD ["node", "dist/server.js"]
Where to Go Next
Once a single container feels comfortable, the next steps are usually docker-compose for running an app alongside its database and other services locally, and a registry (Docker Hub, GitHub Container Registry, or a cloud provider's registry) for pushing images so they can be deployed elsewhere.
