FROM
Set base image for the build.
FROM ubuntu:20.04Use specific version:
FROM node:14-alpineMulti-stage build:
FROM node:14 AS build
FROM nginx:alpine
RUN
Execute commands during image build.
RUN apt-get update && apt-get install -y python3Multiple commands:
RUN apt-get update && \
apt-get install -y curl && \
rm -rf /var/lib/apt/lists/*
COPY
Copy files from host to image.
COPY app.py /app/Copy directory:
COPY ./src /app/srcCopy with permissions:
COPY --chown=user:group file.txt /app/
ADD
Copy files with additional features (extract archives, URL support).
ADD archive.tar.gz /app/From URL:
ADD https://example.com/file.txt /app/
WORKDIR
Set working directory for subsequent instructions.
WORKDIR /appCreates directory if it doesn't exist.
CMD
Default command to run when container starts.
CMD ["python3", "app.py"]Shell form:
CMD python3 app.py
ENTRYPOINT
Configure container to run as executable.
ENTRYPOINT ["python3", "app.py"]Combined with CMD:
ENTRYPOINT ["python3"]
CMD ["app.py"]
EXPOSE
Document which ports container listens on.
EXPOSE 80Multiple ports:
EXPOSE 80 443
ENV
Set environment variables.
ENV APP_ENV=productionMultiple variables:
ENV APP_ENV=production \
LOG_LEVEL=info
ARG
Define build-time variables.
ARG VERSION=1.0Use in Dockerfile:
ARG NODE_VERSION=14
FROM node:${NODE_VERSION}
VOLUME
Create mount point for external volumes.
VOLUME /dataMultiple volumes:
VOLUME ["/data", "/logs"]
USER
Set user for running commands.
USER appuser
LABEL
Add metadata to image.
LABEL version="1.0"
LABEL description="My application"
Complete Example
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]
Multi-Stage Build Example
FROM node:14 AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]