CI/CD & Deployment interview question · Most asked

What are best practices for writing Dockerfiles?

Summary

Use small, pinned base images, multi-stage builds to keep build tools out of the runtime image, order layers so dependencies are cached before source code, run as a non-root user, add a .dockerignore, use exec-form CMD, and scan images for vulnerabilities.

Longer Answer

Keep one main process per container, configure via environment variables, and log to stdout/stderr.

Code Example

FROM python:3.13-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --wheel-dir /wheels -r requirements.txt

FROM python:3.13-slim
RUN useradd --create-home app
WORKDIR /app
COPY --from=build /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
COPY . .
USER app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Key Points

  • Small pinned base images
  • Multi-stage builds
  • Cache-friendly layer order
  • Non-root user
  • Scan images

More most-asked CI/CD & Deployment questions

← All CI/CD & Deployment questions