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
- What's the difference between continuous integration, continuous delivery and continuous deployment?
- What stages does a typical CI/CD pipeline contain?
- Compare rolling, blue-green and canary deployments.
- How do you run database migrations without downtime?
- What's the difference between liveness and readiness probes?
- How should secrets be handled in CI/CD pipelines?