Writing a Dockerfile
A Dockerfile is a script that describes how to build your own image, step by step.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Reading it line by line
FROMpicks a base image to start from, here a lightweight Node.js image.WORKDIRsets the working directory inside the container for every instruction after it.COPYcopies files from your machine into the image.RUNexecutes a command while building the image (installing dependencies, here).EXPOSEdocuments which port the container listens on.CMDis the command that runs when a container starts from this image.
Building and running your image
docker build -t my-app .
docker run -p 3000:3000 my-app
-t my-app tags the image with a name so you can refer to it later instead of a random id.
WARNING
Copying package*.json and running npm install before copying the rest of your code lets Docker reuse that cached layer when only your source changes, skipping a slow reinstall on every build.