04 - Dockerfile Basics
Dockerfile basics
We often need custom images to ship our own apps. Dockerfile defines how to build them.
What is a Dockerfile?
A text file of instructions telling Docker how to build an image—automated, consistent, repeatable.
Syntax basics
Instructions are uppercase, executed in order; each creates a new layer.
Common instructions
FROM
FROM ubuntu:20.04
FROM alpine:3.14
LABEL
LABEL maintainer="your-email@example.com"
LABEL version="1.0"
RUN
RUN apt-get update && apt-get install -y \
nginx \
curl \
&& rm -rf /var/lib/apt/lists/*
Combine related commands to reduce layers.
COPY vs ADD
COPY app.js /app/
ADD app.tar.gz /app/
Prefer COPY unless you need ADD features (auto-extract/URL).
WORKDIR
WORKDIR /app
ENV
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE
EXPOSE 80
Declares intent; still map ports with -p at runtime.
CMD vs ENTRYPOINT
CMD ["nginx", "-g", "daemon off;"]
ENTRYPOINT ["nginx", "-g", "daemon off;"]
- ENTRYPOINT is the fixed command; CMD supplies default args and can be overridden by
docker run.
VOLUME
VOLUME ["/data"]
USER
USER nginx
Best practices
1) Multi-stage builds
# build stage
FROM golang:1.17 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
# final image
FROM alpine:3.14
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]
2) Minimize layers
Merge related RUN steps.
3) .dockerignore
node_modules
.git
*.log
4) Pin versions, avoid latest
FROM node:14.17.0-alpine
5) Clean caches in the same RUN
RUN apt-get update && apt-get install -y \
package1 \
package2 \
&& rm -rf /var/lib/apt/lists/*
Example: Node.js app image
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
Build and run
Build
docker build -t myapp:1.0 .
Run
docker run -d -p 3000:3000 --name myapp-container myapp:1.0
Summary
You learned Dockerfile syntax, key instructions, and best practices. Next: Docker data management (volumes, bind mounts, tmpfs).