A service name identifies a Docker Compose service and becomes its hostname inside the Compose network. Instead of calling another container through localhost, use its service name, such as http://web:8080. section 6.4 section 6.4.1
Calling an NGINX service
With services named web and my-nginx-service, enter the web container with docker compose exec web /bin/bash and run curl http://my-nginx-service or curl http://my-nginx-service:80. The request succeeds even though my-nginx-service exposes no port to the host, because it is reachable from the Compose network. section 6.4.1
Use service names to connect containers and keep configurations consistent:
- Name the service in compose.yaml; Compose uses that name for service discovery. section 6.4.1
- Connect application containers to databases such as Redis through the database service name rather than the host machine’s hostname. section 6.4.2
- Keep service names synchronized across Compose and NGINX configuration; names such as web and api become upstream addresses. section 9.1.1
- After renaming or removing services, use docker compose down --remove-orphans before rebuilding the environment. section 6.4.2
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:
Inspect a minimal Compose file where my-nginx-service is reachable by name from web while remaining private to the Compose network. section 6.4.1
