Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Docker Interview Questions and Answers

By Kokil Thapa | Last reviewed: August 2026

Preparing for a backend or DevOps role requires more than memorizing definitions; you need to demonstrate operational maturity. This guide provides practical Docker interview questions and answers grounded in production reality rather than textbook theory. Whether you are applying for a Laravel developer position or a dedicated platform engineering role, interviewers in 2026 expect you to understand isolation primitives, networking gotchas, and secure image construction.

What are the core architectural concepts behind Docker interview questions and answers?

The most common failure point in technical screens is confusing containers with virtual machines. When an interviewer asks "What is a container?", they are testing your understanding of Linux kernel primitives. A container is not a lightweight VM; it is a collection of constrained processes running directly on the host kernel.

You must articulate two specific mechanisms:

  • Namespaces: These provide isolation. They create the illusion of a private system by partitioning kernel resources. There are seven namespaces in modern Linux (as of kernel 5.x+): PID, NET, MNT, UTS, IPC, USER, and CGROUP. When you run docker run, the daemon requests these namespaces from the kernel.
  • Control Groups (cgroups v2): These provide resource limitation. While namespaces hide resources, cgroups enforce limits. They prevent a single container from starving the host of CPU, memory, or I/O bandwidth. In production, failing to set cgroup limits is a primary cause of noisy-neighbor issues.
Linux Host Kernel (Shared)Namespaces (Isolation) + Cgroups v2 (Resource Limits)Container A (PHP-FPM)PID NamespaceNET NamespaceMNT NamespaceCgroup LimitsContainer B (Nginx)PID NamespaceNET NamespaceMNT NamespaceCgroup LimitsContainer C (MySQL)PID NamespaceNET NamespaceMNT NamespaceCgroup Limits
Docker architecture relies on shared kernel primitives rather than hardware virtualization

In my experience working on production Laravel applications, explaining this distinction matters because it dictates your debugging strategy. You cannot SSH into a container like a VM; you inspect namespaces. If a candidate mentions "lightweight VM," I probe deeper. If they mention "process isolation via namespaces," I know they have operated real systems.

How do you optimize Dockerfiles for production security and performance?

Interviewers ask about Dockerfiles to test if you understand layer caching and attack surface reduction. A correct answer involves multi-stage builds and minimal base images. Never ship build tools, compilers, or package managers in your production artifact.

Multi-stage build pattern

For a PHP/Laravel application, your build stage installs Composer dependencies and compiles frontend assets. Your production stage copies only the resulting artifacts into a clean runtime image. This reduces image size from ~800MB to ~150MB and eliminates entire classes of CVEs associated with dev toolchains.

# Build Stage
FROM php:8.4-cli AS builder
WORKDIR /app
COPY composer.json composer.lock ./
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer install --no-dev --optimize-autoloader --ignore-platform-reqs

# Production Stage  
FROM php:8.4-fpm-alpine AS production
WORKDIR /var/www/html
COPY --from=builder /app/vendor ./vendor
COPY . .
RUN chown -R www-data:www-data storage bootstrap/cache
USER www-data
EXPOSE 9000
CMD ["php-fpm"]

Layer ordering matters

Docker caches layers sequentially. Place frequently changing instructions (like COPY . .) at the bottom and stable instructions (RUN apk add) at the top. Invalidating a cache layer forces a rebuild of all subsequent layers. On projects where CI minutes cost money, proper layer ordering can reduce build times by 60-80%.

Distroless and Alpine considerations

Alpine Linux uses musl libc instead of glibc. While smaller, this causes compatibility issues with some PHP extensions and Node.js native modules. In 2026, many teams prefer Debian-based distroless images or slim variants for better compatibility without the bloat. Always verify your specific workload before defaulting to Alpine solely for size metrics.

What are the different Docker networking modes and when should you use each?

Networking questions separate operators from users. You must explain the four primary drivers and their trade-offs. Most production issues I encounter stem from misunderstanding bridge networking versus host networking.

Network ModeUse CasePerformanceIsolation
bridge (default)Standard microservices, web appsNAT overhead (~5-10%)High (separate subnet)
hostHigh-throughput databases, monitoring agentsNative (zero overhead)None (shares host ports)
noneSecurity-sensitive batch processingN/AComplete (no stack)
overlaySwarm/Kubernetes cross-node communicationVXLAN encapsulation costMulti-host isolated
Bridge Mode (Default)docker0 Bridge (172.17.0.1)Container A172.17.0.2Container B172.17.0.3iptables NAT / Port MappingExternal → Host IP:Port → NAT → ContainerHost ModeHost eth0 (Direct Access)Container CShares Host Net NSZero Overhead / No NATExternal → Host IP:Port → Container (Direct)
Bridge mode adds NAT overhead but provides isolation; host mode sacrifices isolation for raw throughput

A practical scenario: On a legal-tech portal handling document uploads, we ran the PHP-FPM workers in bridge mode for security but placed Redis in host mode because inter-process latency directly impacted user session performance. The key is justifying the trade-off based on measurable requirements, not dogma.

How do you debug a crashing container that exits immediately?

This is the most frequent hands-on question. "It works locally" is unacceptable. You need a systematic approach using Docker's introspection tools. Memorize this sequence:

  1. Check exit codes: Run docker ps -a to see the STATUS column. Exit code 137 means OOMKilled (increase memory limit). Exit code 1 indicates application error. Exit code 0 means clean exit (maybe your entrypoint script finished prematurely).
  2. Inspect logs: docker logs --tail 100 <container> captures stdout/stderr. If logs are empty, the process may be logging to a file inside the container instead of standard streams—a critical anti-pattern.
  3. Override entrypoint: If the app crashes too fast to read logs, run docker run -it --entrypoint /bin/sh <image>. This drops you into an interactive shell with the same environment. Manually execute your startup command to observe errors in real-time.
  4. Inspect configuration: docker inspect <container> reveals environment variables, mount points, and resource limits. Mismatched env vars or missing volume mounts cause more failures than code bugs.
  5. Check resource exhaustion: docker stats shows live CPU/memory usage. If memory hits the limit right before crash, you have a leak or undersized allocation.

On a recent e-commerce project, a queue worker kept dying silently. Logs showed nothing. Overriding the entrypoint revealed the PHP process was writing errors to /var/log/php-fpm.log instead of stderr. We fixed the logging configuration to output to /dev/stderr, and suddenly the root cause appeared in docker logs. This pattern—ensuring all output goes to standard streams—is non-negotiable in containerized environments.

What distinguishes volumes from bind mounts in persistent storage strategies?

Data persistence questions test whether you understand state management. Containers are ephemeral; data must survive restarts and redeployments. The distinction between volumes and bind mounts determines backup strategy, portability, and performance.

Named VolumeContainer /app/dataMount Point/var/lib/docker/volumes/myapp_data/_data(Docker-managed lifecycle)✓ Portable across hosts✓ Backup via docker volume commandsBind MountContainer /app/configMount Point/home/user/project/config(Host filesystem path)(OS-dependent permissions)⚠ Development hot-reload only⚠ Permission issues on Linux/macOS
Named volumes are managed by Docker and portable; bind mounts reference host paths and are development-only

Named volumes (docker volume create) live in /var/lib/docker/volumes/. Docker manages their lifecycle. They are portable across hosts, support volume drivers for cloud storage, and avoid permission mapping headaches. Use them for databases, uploaded media, and any production state.

Bind mounts map a host directory directly into the container. They are essential for development (live code reloading) but dangerous in production. Host filesystem permissions, SELinux contexts, and path differences between macOS/Linux/Windows cause subtle failures. I have seen deployments fail because a bind mount referenced a path that existed on the developer's MacBook but not on the Ubuntu server.

Rule of thumb: If the data must survive container deletion and be backed up independently, use a named volume. If you are actively editing files during development, use a bind mount. Never mix these patterns accidentally.

Mastering Docker Interview Questions and Answers for Production Roles

Success in technical interviews comes from demonstrating operational judgment, not reciting documentation. When preparing Docker interview questions and answers, focus on explaining trade-offs: why you chose bridge over host networking, why multi-stage builds matter for security, how you debug silent failures systematically. Interviewers want evidence that you have maintained systems under pressure, not just built tutorials.

Practice articulating the kernel primitives behind containers, the caching implications of layer ordering, and the persistence strategies for stateful workloads. These topics separate senior engineers from juniors. If you are preparing for a backend role involving containerized PHP or Node.js applications, review our guide on building REST APIs in Laravel to understand how application architecture intersects with container design. For broader career preparation in Nepal's tech market, the article on full-stack developer skills covers complementary competencies.

When you can explain not just what a Docker feature does but why it exists and when to avoid it, you demonstrate the depth that hiring managers seek. Prepare concrete examples from your own debugging sessions. The best answers sound like war stories, not textbook excerpts.

Ready to validate your knowledge against real production scenarios? Contact me for technical consulting or team training on containerized PHP/Laravel deployments.

Frequently Asked Questions

Docker containers share the host OS kernel and isolate processes at the application level, while VMs run full guest operating systems with dedicated kernels. Containers start in seconds and use megabytes of RAM; VMs take minutes and require gigabytes. For most web applications I deploy on Ubuntu servers, containers provide sufficient isolation without the overhead of virtualization.

Use multi-stage builds to separate build dependencies from runtime artifacts. Start with php:8.4-cli-bookworm for Composer installs, then copy only vendor/ and app code into a slim alpine or bookworm-slim final stage. Remove dev packages with composer install --no-dev --optimize-autoloader. On production Laravel projects, this routinely drops images from 1.2GB to under 300MB.

172.17.0.0/16.

Never bake secrets into images. Use Docker Secrets with Swarm mode or pass environment variables at runtime via docker compose config files excluded from version control. For Laravel apps, mount .env as a read-only volume or inject via orchestrator secret stores. In my Deployer 7 workflows outside Docker, I symlink persistent .env files; the same principle applies inside containers.

The main process finished or crashed. Check logs with docker logs . Ensure your CMD runs a foreground process, not a daemon. For PHP-FPM, use php-fpm -F. Verify the entrypoint script has execute permissions and correct shebang lines. Missing environment variables or failed health checks also cause immediate exits during orchestration startup sequences.

Unix socket /var/run/docker.sock; TCP 2375 unencrypted or 2376 TLS when enabled.

Use named volumes or bind mounts declared in docker-compose.yml. Named volumes like db_data:/var/lib/mysql are managed by Docker and survive container removal. Bind mounts map host paths directly but require correct ownership matching the container user. On production MySQL 8.4 containers, I always use named volumes and schedule mysqldump backups separately to avoid relying solely on volume persistence.

COPY transfers local files into the image transparently. ADD does the same but also auto-extracts tar archives and supports remote URLs. Best practice is using COPY unless you specifically need extraction behavior, since ADD's implicit magic makes builds harder to reason about. Explicitly extracting archives in a RUN step gives clearer layer caching and debugging visibility during CI pipeline failures.

Use docker exec -it sh to get an interactive shell. Install debugging tools temporarily with apt-get or apk add inside the container. For PHP, enable Xdebug or check error_log paths. Inspect environment with printenv, verify configs with cat, and test connectivity with curl. Remember that changes made inside running containers are ephemeral unless committed, so fix root causes in Dockerfiles instead.

Docker Compose suits single-server deployments, development environments, and small teams managing fewer than ten services. Kubernetes handles multi-node clusters, auto-scaling, and complex orchestration needs. Most Nepal-based clients I work with run single EC2 instances where Compose plus Deployer 7 provides adequate reliability without Kubernetes operational overhead. Choose K8s only when horizontal scaling or team size justifies the complexity tax.

Run containers as non-root users with USER directive in Dockerfiles. Drop capabilities with cap_drop: ALL and add back only required ones. Enable read-only root filesystems where possible. Avoid privileged mode entirely. Scan images with Trivy or Snyk before deployment. On legal-tech portals handling sensitive documents, I enforce these restrictions strictly and audit container configurations during every release cycle.

Host directory ownership mismatches the container UID/GID. Fix by chown -R on the host path to match the container user, or set user: "1000:1000" in compose files. SELinux or AppArmor may also block access; check audit logs and apply appropriate labels. This issue appears frequently when mounting Laravel storage directories or WordPress uploads folders into fresh containers during initial setup.

Docker itself is free; costs come from underlying infrastructure. A 2GB RAM VPS in Kathmandu data centers runs Rs 1,500-3,000/month (~USD 11-22), same whether running bare metal or containers. Cloud providers charge identically for compute regardless of containerization. Savings emerge from higher density: fitting three containerized apps on one VPS that previously needed separate instances reduces total hosting spend proportionally.

Run docker compose build --no-cache or docker build --no-cache .. This forces all layers to regenerate, ensuring updated Composer packages, npm modules, or system libraries are fetched fresh. Use selectively since full rebuilds are slow. For routine updates, invalidate specific layers by moving frequently-changing instructions like COPY package.json before expensive RUN steps to leverage partial cache hits effectively.

Yes, but treat them as separate long-running services, not part of the web container. Define dedicated worker services in docker-compose.yml with restart: unless-stopped policies. Mount shared storage volumes for job payloads. Configure supervisor or s6-overlay to manage multiple worker processes within each container. Monitor memory limits closely since PHP workers leak over time; set max-memory thresholds and implement graceful restarts to prevent silent queue processing failures.

Share this article

Quick Contact Options
Choose how you want to connect me: