Mastering the Art of Building Images and composing services.
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.
# 1. Start from a base image FROM node:18-alpine # 2. Set working directory WORKDIR /app # 3. Copy package files COPY package*.json ./ # 4. Install dependencies RUN npm install # 5. Copy source code COPY . . # 6. Expose port EXPOSE 3000 # 7. Start the app CMD ["npm", "start"]
For Building Docker Image
docker build -t my-app .docker build -t my-app:v1 .docker run -p 3000:3000 my-appWe select an existing node image for ease. We could use Ubuntu and manually install Node, but this is efficient.
Defines where inside the container we will keep our code base.
We copy only package.json first. This is crucial for caching!
Installs all dependencies defined in package.json.
Now we copy the rest of the codebase.
Documentation step. Tells users which port the app listens on by default.
RUNTIME: This command runs automatically when someone starts the container.
In the industry, we don't just want our code to run; we want our deployment pipelines to be fast and efficient. Docker is "smart"—it caches layers. If a layer and all previous layers haven't changed, Docker reuses the cached version.
npm install runs on EVERY build.npm install comes from CACHE.Imagine drawing on transparent plastic sheets (projector transparencies).
COPY or RUN command puts a fresh transparent sheet on top.Reuse
If you build 5 different apps that all use FROM node:18, Docker only downloads/stores that bottom sheet once.
Invalidation
If you change a sheet in the middle, Docker must throw away that sheet and every sheet above it. This is why we put stable sheets (dependencies) at the bottom!
Executes commands DURING the build process. It creates a new layer in the image.
Use Case
(Happens when you run docker build)
Executes commands AUTOMATICALLY when the container starts.
Triggers When:
docker run -p ...docker start ..."Internally, my image runs this command to wake up."
(Happens when you run the image)
RUN is like preparing the kitchen (buying ingredients, chopping types).
CMD is like opening the restaurant (serving the food).
Once you've built your image, it lives only on your laptop. To share it (or deploy it to a server), you need to push it to a registry like Docker Hub.
Go to hub.docker.com, sign up, and click Create Repository.
my-node-apppush, it defaults to a Public repo.Connect your terminal to your account.
This is crucial! Your image name MUST start with your Docker Hub username.
If error occurs like this: tag does not exist: <username>/my-node-app:v1
Run this command to fix it:
Uploads (pushes) your layers to the cloud.