Services and Networks
In a multi‑container application, services need to communicate with each other. Compose makes this simple by automatically creating a network for your project and allowing services to reach each other by their service names.
Service Discovery
When you run
docker compose up, Compose creates a dedicated network for the project. Each service is added to that network with a hostname equal to its service name. So, if you have a service named db, other services can connect to it using db as the hostname.Example: Web + Database
Consider a simple WordPress setup with MySQL:
services:
wordpress:
image: wordpress
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: secret
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: rootsecret
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: secretThe WORDPRESS_DB_HOST environment variable uses the service name db, which Compose resolves to the correct IP.Custom Networks
You can define multiple networks to isolate services. For example, a frontend network for web servers and a backend network for databases.
services:
web:
image: nginx
networks:
- frontend
app:
image: myapp
networks:
- frontend
- backend
db:
image: postgres
networks:
- backend
networks:
frontend:
backend:Depends On
The
depends_on option tells Compose to start services in a specific order. It does not wait for the service to be ready (only ensures it's started). For waiting, you may need additional scripts or use tools like wait-for-it.Two Minute Drill
- Services can communicate using service names as hostnames.
- Compose creates a default network for the project automatically.
- Use
depends_onto control startup order (but not readiness). - Define custom networks to isolate parts of your application.
Need more clarification?
Drop us an email at career@quipoinfotech.com
