stackademic

The leading education platform for anyone with an interest in software development.

Docker Networking

How containers communicate with each other and the outside world

Overview

Docker networking controls how containers talk to each other, to the host, and to the internet. Each container gets its own network namespace, and Docker connects them through virtual networks. Understanding networks lets you link an app to its database or expose a service to the outside world safely.

Syntax / Usage

The most common network type is a user-defined bridge network, which gives containers automatic DNS resolution by container name. You create a network and attach containers to it with --network.

# Create a user-defined bridge network
docker network create appnet

# Run containers on the same network
docker run -d --name db --network appnet postgres
docker run -d --name api --network appnet -p 3000:3000 myapi

# List and inspect networks
docker network ls
docker network inspect appnet

Examples

Connect an application to a database by container name (DNS works on user-defined networks):

docker network create shopnet
docker run -d --name redis --network shopnet redis
# The app can now reach the cache at hostname "redis:6379"
docker run -d --name web --network shopnet -p 8080:80 mystore

Publish a container port to the host so a browser can reach it:

docker run -d -p 8080:80 nginx

Common Mistakes

  • Relying on the default bridge network, where DNS by container name does not work
  • Confusing EXPOSE (documentation only) with -p (actually publishes a port)
  • Publishing a port but binding the app to 127.0.0.1 inside the container
  • Port conflicts when two containers map to the same host port
  • Forgetting that containers on different networks cannot reach each other

See Also

docker-introduction docker-compose docker-volumes