Docker Compose는 각 서비스에 하나의 네트워크를 생성하고, 서비스들은 이를 통해 통신이 가능하다. 이 기능은 사용자가 IP주소를 기억하지 않아도 되게 한다. 이 이점이 Docker Compose를 강력한 tool로 만든다.
FROM ubuntu
RUN apt-get update && \
apt-get install -y iputils-ping
CMD bash
Dockerfile과 yaml파일은 같은 경로에 두어야 한다.
version: "3"
services:
service-1:
image: alpine
build:
context: .
container_name: service-1
command: "ping service-2 -c 3"
service-2:
image: alpine
container_name: service-2
command: "ping service-1 -c 3"
각 서비스는 서로에게 3번 핑을 보낸다.
command: "ping service -c 3"
docker-compose up 명령어를 통해 실행이 가능하다.
명령어 입력
docker-compose up
실행결과
service-1 | PING service-2 (172.18.0.2): 56 data bytes
service-2 | PING service-1 (172.18.0.3): 56 data bytes
service-1 | 64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.054 ms
service-2 | 64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.056 ms
service-2 | 64 bytes from 172.18.0.3: seq=1 ttl=64 time=0.022 ms
service-1 | 64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.042 ms
service-1 | 64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.041 ms
service-1 |
service-2 | 64 bytes from 172.18.0.3: seq=2 ttl=64 time=0.041 ms
service-1 | --- service-2 ping statistics ---
service-2 |
service-1 | 3 packets transmitted, 3 packets received, 0% packet loss
service-2 | --- service-1 ping statistics ---
service-1 | round-trip min/avg/max = 0.041/0.045/0.054 ms
service-2 | 3 packets transmitted, 3 packets received, 0% packet loss
service-2 | round-trip min/avg/max = 0.022/0.039/0.056 ms
service-1 exited with code 0
service-2 exited with code 0
성공적으로 두 서비스가 핑을 3번 보낸 것을 확인할 수 있다.
출처:
https://grahambryan.medium.com/networking-with-docker-compose-a-simple-ping-example-7b6979dfc94b