Docker interview question · Most asked
How does Docker networking work? Explain bridge, host and user-defined networks.
Summary
By default containers attach to a bridge network with private IPs and reach the outside world through NAT; -p 8080:80 publishes a container port on the host. User-defined bridge networks add automatic DNS, so containers resolve each other by name, and better isolation. --network host shares the host's network stack (no isolation, no port mapping). Overlay networks span multiple hosts (Swarm).
Longer Answer
Containers on the default bridge cannot resolve each other by name, which is why Docker Compose creates a user-defined network per project where services reach each other as http://api:8000. Inside a container, localhost is the container itself, not the host or another container, a frequent beginner mistake; use the service name, or host.docker.internal (Docker Desktop, or with --add-host) to reach the host. Publishing ports binds to all interfaces by default (0.0.0.0), so bind to 127.0.0.1: for local-only access.
Key Points
- Bridge + NAT; -p publishes ports.
- User-defined networks provide DNS.
- Host network shares the host stack.
- localhost inside a container is the container.
More most-asked Docker questions
- What is the difference between an image and a container, and how do image layers work?
- What is a container, and how does it differ from a virtual machine?
- What are multi-stage builds, and why use them?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- What are Dockerfile best practices for production images?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- How do you secure Docker containers and images?