0% found this document useful (0 votes)
4 views9 pages

Docker SpringBoot Interview Questions

This document provides a comprehensive set of interview questions and answers focused on Docker and Spring Boot for candidates with two years of experience. It covers core Docker concepts, Docker architecture, multi-stage builds, containerization of Spring Boot applications, and best practices for production readiness. Additionally, it addresses how Docker integrates into CI/CD pipelines and offers tips for effective debugging and configuration management.

Uploaded by

honeyrathore2712
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Docker SpringBoot Interview Questions

This document provides a comprehensive set of interview questions and answers focused on Docker and Spring Boot for candidates with two years of experience. It covers core Docker concepts, Docker architecture, multi-stage builds, containerization of Spring Boot applications, and best practices for production readiness. Additionally, it addresses how Docker integrates into CI/CD pipelines and offers tips for effective debugging and configuration management.

Uploaded by

honeyrathore2712
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Docker & Spring Boot

Interview Questions & Answers


For 2 Years of Experience
20 Questions 2 Sections 2 YOE Level
Total Core + Spring Boot Mid-level Focus

Docker Core Concepts


Q1. What is Docker and how does it differ from a Virtual Machine?
Answer:
Docker is a containerization platform that packages applications with their dependencies into lightweight,
portable containers. Unlike Virtual Machines, Docker containers share the host OS kernel.
Key differences:
• VM: Runs a full OS with hypervisor overhead; Docker: Shares host kernel, much lighter
• VM: Takes minutes to boot; Docker: Starts in milliseconds
• VM: Uses GBs of space; Docker: Uses MBs via layered images
• VM: Strong isolation; Docker: Process-level isolation using namespaces & cgroups

💡 Tip: Mention that Docker uses Linux namespaces for isolation and cgroups for resource limits.

Q2. Explain Docker architecture — Daemon, Client, Registry.


Answer:
Docker follows a client-server architecture with three main components:
• Docker Daemon (dockerd): Runs on the host, manages containers, images, networks, volumes
• Docker Client (docker CLI): Sends commands to the daemon via REST API
• Docker Registry: Stores Docker images (Docker Hub is the default public registry)

docker build -t myapp:1.0 .


docker push myregistry/myapp:1.0
docker pull myregistry/myapp:1.0

Q3. What is the difference between a Docker Image and a Docker Container?
Answer:
A Docker Image is a read-only template — a blueprint for creating containers. It is built in layers (base
OS, dependencies, app code). A Container is a running instance of an image — it adds a writable layer
on top of the image layers.
• Image: Static, stored on disk, immutable
• Container: Dynamic, running process with its own writable layer
• Multiple containers can run from the same image independently

💡 Tip: Images are like a class definition; containers are like object instances.

Q4. Explain Docker layers and how caching works during builds.
Answer:
Every instruction in a Dockerfile (FROM, RUN, COPY, etc.) creates a new layer. Docker caches each
layer and reuses it if nothing has changed up to that point in the build.
• If a layer changes, all layers below it are invalidated and rebuilt
• Order Dockerfile instructions from least to most frequently changing for best cache usage
• COPY source code AFTER installing dependencies to avoid reinstalling on every code change

FROM openjdk:17-slim
WORKDIR /app
COPY [Link] .
RUN mvn dependency:go-offline # cached if [Link] unchanged
COPY src ./src
RUN mvn package -DskipTests

💡 Tip: Always put dependency installation before copying source code — this is the most common
interview follow-up.

Q5. What is a multi-stage build and why is it important?


Answer:
Multi-stage builds use multiple FROM instructions in one Dockerfile. You build in one stage and copy only
the necessary artifacts to the final stage, keeping the production image small and clean.

# Stage 1: Build
FROM maven:3.9-openjdk-17 AS builder
WORKDIR /app
COPY [Link] .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests

# Stage 2: Runtime (final image)


FROM openjdk:17-jre-slim
WORKDIR /app
COPY --from=builder /app/target/*.jar [Link]
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "[Link]"]

💡 Tip: The final image has no Maven, no source code — only the JRE and JAR. Much smaller and
more secure.
Q6. What is the difference between CMD and ENTRYPOINT?
Answer:
Both define what runs when a container starts, but behave differently:
• ENTRYPOINT: Defines the main executable — cannot be overridden by docker run arguments
(without --entrypoint flag)
• CMD: Provides default arguments that CAN be overridden by docker run arguments
• Best practice: Use ENTRYPOINT for the command, CMD for default arguments

ENTRYPOINT ["java", "-jar", "[Link]"]


CMD ["--[Link]=prod"]

# Override CMD at runtime:


docker run myapp --[Link]=dev

Q7. What are Docker Volumes and when would you use them over bind mounts?
Answer:
Volumes are Docker-managed storage that persists beyond container lifecycle. Bind mounts map a host
directory directly into a container.
• Volumes: Managed by Docker, portable, safer for production data (databases, logs)
• Bind mounts: Direct host path mapping, useful for development (live code reload)
• Use volumes for production data persistence; bind mounts for local dev workflows

# Named volume (production)


docker run -v postgres-data:/var/lib/postgresql/data postgres

# Bind mount (development)


docker run -v $(pwd)/src:/app/src myapp

Q8. How does Docker networking work? Explain bridge, host, and none networks.
Answer:
Docker provides several network drivers:
• bridge (default): Containers on the same bridge can communicate; NAT for external access
• host: Container shares host network stack directly — no port mapping needed, better
performance
• none: No networking — fully isolated container
• overlay: Multi-host networking for Docker Swarm
• Custom bridge networks allow containers to reach each other by service name (DNS resolution)

# Create custom network


docker network create my-app-net

# Containers on same network can ping by name


docker run --network my-app-net --name db postgres
docker run --network my-app-net --name app myapp
Q9. What is Docker Compose and how have you used it?
Answer:
Docker Compose is a tool for defining and running multi-container applications using a YAML file (docker-
[Link]). It manages services, networks, and volumes together.
• Defines all services in one file — easy to spin up entire stack with one command
• Handles startup order with depends_on
• Creates a shared network by default — services reach each other by name

version: '3.8'
services:
app:
build: .
ports:
- '8080:8080'
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydb
depends_on:
- db
db:
image: postgres:15
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:

Q10. How do you manage secrets and environment variables securely in Docker?
Answer:
Never hardcode secrets in Dockerfiles or docker-compose files. Use:
• Environment variables via .env files (for local dev only, not production)
• Docker Secrets (for Swarm mode) — secrets mounted as files in /run/secrets/
• Kubernetes Secrets or cloud provider secret managers (AWS SSM, HashiCorp Vault) in
production
• Never build secrets into image layers — they persist in image history

# .env file (never commit to git)


DB_PASSWORD=supersecret

# [Link]
environment:
- DB_PASSWORD=${DB_PASSWORD}

# Or use external secret manager at runtime

💡 Tip: Run 'docker history myimage' to see what's baked into layers — secrets will be visible.
Docker with Spring Boot
Q11. How do you containerize a Spring Boot application?
Answer:
There are three main approaches:
• 1. Dockerfile with multi-stage build (most control)
• 2. Spring Boot Maven/Gradle plugin with buildpacks: mvn spring-boot:build-image
• 3. Jib plugin (Google) — builds optimized Docker image without a Dockerfile

# Using Spring Boot plugin (simplest)


mvn spring-boot:build-image -[Link]=myapp:1.0

# Or traditional Dockerfile approach


FROM openjdk:17-jre-slim
COPY target/[Link] [Link]
ENTRYPOINT ["java","-jar","/[Link]"]

💡 Tip: Mention Jib if you want to impress — it builds without Docker daemon and creates optimized
layers.

Q12. How do you pass Spring Boot application properties to a Docker container?
Answer:
Spring Boot reads configuration from environment variables automatically, following a naming convention.
This is the cleanest way to configure containers.
• [Link] → SPRING_DATASOURCE_URL (dots become underscores, uppercase)
• Pass via docker run -e flag, docker-compose environment section, or Kubernetes
ConfigMap/Secret
• Spring profiles can be activated via SPRING_PROFILES_ACTIVE env variable

docker run -e SPRING_PROFILES_ACTIVE=prod \


-e SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydb \
-e SPRING_DATASOURCE_PASSWORD=secret \
myapp:1.0

Q13. How do you configure health checks for a Spring Boot container?
Answer:
Spring Boot Actuator provides /actuator/health endpoint. Docker can use this for health checks to know
when a container is truly ready.
• Add spring-boot-starter-actuator dependency
• Configure HEALTHCHECK in Dockerfile or docker-compose
• Docker restarts unhealthy containers automatically

# Dockerfile
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f [Link] || exit 1

# docker-compose
healthcheck:
test: ["CMD", "curl", "-f", "[Link]
interval: 30s
timeout: 10s
retries: 3
start_period: 60s

💡 Tip: Set start_period to at least 60s for Spring Boot apps — they take time to warm up.

Q14. How do you handle JVM memory settings inside a Docker container?
Answer:
Old JVM versions (pre Java 8u191) didn't respect container memory limits and would use host RAM,
causing OOM kills. Modern JVMs handle this better but you should still set limits explicitly.
• Use -XX:MaxRAMPercentage to set JVM heap as a percentage of container memory
• Always set Docker memory limits — never let containers use unlimited RAM
• Use -XX:+UseContainerSupport (default in JDK 11+) for container awareness

# Dockerfile
ENTRYPOINT ["java",
"-XX:MaxRAMPercentage=75.0",
"-XX:+UseContainerSupport",
"-jar", "[Link]"]

# docker run with memory limit


docker run -m 512m myapp:1.0
# JVM will use ~384MB heap (75% of 512MB)

💡 Tip: Set MaxRAMPercentage to 75% — leave 25% for the JVM's non-heap memory (metaspace,
threads, GC).

Q15. How do you set up a local development environment with Docker Compose for a
Spring Boot app with PostgreSQL and Redis?
Answer:
A complete docker-compose setup for Spring Boot with multiple dependencies:

version: '3.8'
services:
app:
build:
context: .
target: development
ports:
- '8080:8080'
- '5005:5005' # remote debug port
environment:
SPRING_PROFILES_ACTIVE: dev
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/appdb
SPRING_REDIS_HOST: redis
volumes:
- ./src:/app/src # live reload
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
image: postgres:15
environment:
POSTGRES_DB: appdb
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user"]
interval: 10s
retries: 5
redis:
image: redis:7-alpine
ports:
- '6379:6379'
volumes:
postgres-data:

Q16. How do you handle database migrations (Flyway/Liquibase) in a Dockerized Spring


Boot app?
Answer:
Flyway or Liquibase runs automatically on Spring Boot startup. In a containerized environment, the key
challenge is ensuring the database is ready before the app starts.
• Use depends_on with service_healthy condition in docker-compose
• Add retry logic or wait-for-it scripts for production orchestration
• In Kubernetes, use init containers to wait for DB readiness
• Never run migrations in parallel from multiple instances — use Spring's
@ConditionalOnMissingBean or migration locks

# [Link]
spring:
flyway:
enabled: true
locations: classpath:db/migration
baseline-on-migrate: true

💡 Tip: Flyway has built-in locking, so multiple Spring Boot instances starting simultaneously won't
double-run migrations.
Q17. How do you configure logging in a containerized Spring Boot application?
Answer:
In Docker, logs should go to stdout/stderr — not files. Docker captures stdout and routes it to the
configured log driver (json-file, fluentd, CloudWatch, etc.).
• Configure Spring Boot to output JSON structured logs for easier parsing
• Never write logs to files inside a container — they're lost when container stops
• Use log aggregation: ELK Stack, Datadog, CloudWatch, or Loki
• Add MDC context (correlationId, traceId) for distributed tracing

# [Link] — JSON logging


logging:
pattern:
console: '{"time":"%d","level":"%p","traceId":"%X{traceId}","msg":"%m"}%n'

# Or use [Link] with JsonEncoder


# Add logstash-logback-encoder dependency

Q18. What Docker best practices do you follow when building Spring Boot images for
production?
Answer:
Production readiness checklist:
• Use multi-stage builds — keep final image as small as possible
• Use specific base image tags (openjdk:17.0.9-jre-slim) — never use 'latest'
• Run as non-root user inside container for security
• Use .dockerignore to exclude .git, target/, test files
• Set JVM memory limits and use MaxRAMPercentage
• Add HEALTHCHECK instruction
• Scan images for vulnerabilities with trivy or Docker Scout
• Tag images with git commit SHA for traceability

# Run as non-root user


FROM openjdk:17.0.9-jre-slim
RUN addgroup --system appgroup && adduser --system appuser --ingroup appgroup
USER appuser
COPY --from=builder /app/target/*.jar [Link]
ENTRYPOINT ["java","-jar","[Link]"]

💡 Tip: Running as root inside a container is a security risk — if the container is compromised, the
attacker gets root.

Q19. How would you debug a Spring Boot application running inside Docker?
Answer:
Several debugging approaches for containerized Spring Boot:
• Remote debugging: expose JVM debug port with -agentlib:jdwp flag, connect IntelliJ/Eclipse
• Check logs: docker logs <container-id> -f --tail 100
• Exec into container: docker exec -it <container-id> /bin/sh
• Use Actuator endpoints: /actuator/health, /actuator/env, /actuator/metrics
• Check resource usage: docker stats <container-id>

# Enable remote debug in Dockerfile


ENTRYPOINT ["java",
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005",
"-jar", "[Link]"]

# Expose debug port


docker run -p 8080:8080 -p 5005:5005 myapp

# Connect IntelliJ: Run > Edit Configurations > Remote JVM Debug > port 5005

Q20. How does Docker fit into a CI/CD pipeline for a Spring Boot application?
Answer:
A typical CI/CD flow integrates Docker at every stage:
• CI: Build JAR → Build Docker image → Run tests in container → Scan for vulnerabilities
• Tag image with git commit SHA and push to registry (ECR, Docker Hub, GCR)
• CD: Pull image by SHA tag → Deploy to staging → Run smoke tests → Promote to production
• Use immutable tags (never redeploy 'latest') — every deployment traceable to a commit

# GitHub Actions example


- name: Build and push Docker image
run: |
IMAGE=myregistry/myapp:${{ [Link] }}
docker build -t $IMAGE .
docker push $IMAGE

- name: Scan for vulnerabilities


run: trivy image myregistry/myapp:${{ [Link] }}

💡 Tip: Always use git SHA as image tag in CI/CD — never 'latest'. This makes rollbacks trivial.

Prepared for 2 Years Experience Level | Docker & Spring Boot Interview Prep

You might also like