Container-to-container communication lets separately running containers exchange data or service requests. Docker Compose creates a shared network so one service can reach another by its service name rather than localhost. section 6.4
A practical Docker Compose workflow is:
- Define the communicating services in compose.yaml. section 6.4.1
- Start the services with docker compose up; Compose creates their default network. section 6.4.1
- Enter one container with docker compose exec and call the other by hostname, such as curl http://my-nginx-service:80. section 6.4.1
- Keep internal services private by omitting host-port declarations when outside access is unnecessary. section 6.4.1
A web container calls NGINX
A web service can request http://my-nginx-service or http://my-nginx-service:80 from inside the Compose network. NGINX returns its standard HTML response, even though the NGINX service exposes no port to the host machine. section 6.4.1
Listing 6.9 NGINX service in Docker Compose
services:
my-nginx-service:
image: nginx
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
environment:
- PORT=8080
volumes:
- mywebdata:/app/data
volumes:
mywebdata:
Use the Compose listing to see a web service and an NGINX service sharing the automatically created network. section 6.4.1
