cd ..
DOCKER

Docker Networking: Connecting Containers and Limiting Resources

Docker Networks: connecting containers and limiting resources

By default, each container is isolated from the others thanks to the net namespace — each has its own network view. But real applications almost never live alone: an API needs to talk to a Redis, a Redis needs to be reachable only by those who need it. That’s what Docker networks are for.

Network commands

CommandFunction
docker network createcreates a network
docker network connectconnects an existing container to a network
docker network disconnectdisconnects a container from a network
docker network lslists existing networks
docker network inspectshows network details, including connected containers
docker network rmremoves a network
docker network pruneremoves networks with no connected containers

Creating a network and connecting containers

docker network create giropops-senhas
docker run -d --name redis \
  --network giropops-senhas \
  -p 6379:6379 redis
docker run -d --name giropops-senhas \
  --network giropops-senhas \
  -e REDIS_HOST=redis \
  -p 5000:5000 cesarsantos96/giropops-senhas:1.0

The key point: two containers on the same network can see each other by name. Docker resolves redis to the correct IP of the redis container through an internal DNS — there’s no need to manually discover or fix IPs. This is exactly what the REDIS_HOST=redis variable, passed with -e, is taking advantage of: it tells the application which hostname to use to find the database.

Limiting CPU and memory

Without limits, a container with a bug or usage spike can consume all available resources on the machine, impacting others. Two docker run flags directly solve this:

docker run -d --name redis \
  --network giropops-senhas \
  -p 6379:6379 \
  --cpus 1 \
  --memory 256m \
  redis

To see the complete list of limit options available for run:

docker container run --help

Conclusion

With networks and resource limits, we now have containers that communicate with each other without relying on fixed IPs, and without the risk of one of them bringing down the entire machine. What’s missing now is to stop typing a giant docker run command every time — and that’s what Docker Compose solves, in the next part of the series.

References

What did you think?