Skip to content

Instantly share code, notes, and snippets.

@mr-karan
Last active March 27, 2019 17:28
Show Gist options
  • Save mr-karan/8ca5ee07a0170596e3e5ecb99ee82e97 to your computer and use it in GitHub Desktop.
Save mr-karan/8ca5ee07a0170596e3e5ecb99ee82e97 to your computer and use it in GitHub Desktop.
docker networks simple explanation

This is a simple docker-compose file. It creates 2 running instances of image (containers) from redis and postgres. Exposes port 9379 for redis and port 9432 for postgres on your local machine

I created a network called backend. You can check ip addr and see the newly created network. The way it works is that, both containers will be on same network bridge. Think of it like a VLAN? network basically does a lot of things behind the scenes, but most importantly it lets you access the other container through the service name defined in docker-compose file. From your redis, if you want to access postgres 5432 port, you can do using db:5432. So host is not localhost it is db. db internally resolves to the private ip of the network interface you saw in ip addr when you created backend network. docker has created an entry in /etc/resolv.conf which is 127.0.0.11. It is an internal dns namesever running in your docker daemon, which resolves all the containers' service name to their private IP address. Makes things really simple.

TL;DR

  • From redis container curl db:5432
  • From postgres container curl redis:6379
version: "3"
services:
  redis:
    image: redis:alpine
    ports:
      - "9379:6379"
    networks:
      - backend
    restart: on-failure

  db:
    image: postgres:11
    ports:
      - "9432:5432"
    networks:
      - backend

networks:
  backend:

Hope that clarifies. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment