Implementation of Docker DNS

Access containers by container's name via DNS

Purpose

  • The containers in a same docker network can communicate each other by their alias, but host machine can’t connect to them by alias or name.
    • Basically, the containers' IPs are changed whenever they are restarted.
      • It makes us hard to manage and connect to the containers.
  • In this section, I aim to share how the host machine communicate with the containers by their containers' names.

동작 원리

  • 도커 이름을 풀이해 줄 수 있는 DNS 서버를 개발
    • 해당 서버의 동작은 아래와 같음.

사전 준비 사항

  • 본 섹션은 호스트 머신과 도커 컨테이너가 직접적인 통신이 가능해야 함.

도커 DNS 구축

도커 DNS 설정

  • hackartist/docker-dns 이미지를 사용
    • 도커 및 쿠버네티스(Kubernetes) DNS 기능 제공
      • cluster.local. 쿠버네티스 검색도메인 제공
  • docker-compose 에 아래의 컨테이너 정보 추가
    • /var/run/docker.sock 은 해당 DNS 는 도커 명령어 인터페이스(CLI) 를 통해서 컨테이너 이름을 IP 주소로 변환
    • 이 과정에서 도커 디먼과 통신을 해야하기 때문에 해당 주소를 마운트 해야함.
dns:
  restart: always
  container_name: dns
  image: hackartist/docker-dns:latest
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  ports:
    - 53:53/udp
  environment:
    - ENABLE_K8S_DNS_LOOKUP=false
    - FALLBACK_DNS=8.8.8.8

DNS 주소 변경

  • 호스트 머신의 DNS 주소를 127.0.0.1 로 변경
    • 구축한 도커 DNS 를 기본 DNS로 사용하도록 설정
    • /etc/resolv.conf 의 내용 또는 네트워크 설정에서 변경할 수 있음.
nameserver 127.0.0.1
nameserver 10.96.0.10
nameserver 8.8.8.8

DNS 서버 테스트

  • nslookup 을 통해서 테스트할 수 있음.
    • 서버가 127.0.0.1 로 나오면 정상 변경이 적용
      • 변경이 되지 않은 경우에는 네트워크를 비활성화 후에 다시 활성화하여 확인
    • 서버가 127.0.0.1 로 정상적으로 변경되었는데, 검색이 안되면 아래의 내용 확인
Server:		127.0.0.1
Address:	127.0.0.1#53

Name:	dns
Address: 172.51.0.3