docker-compose
- Go course
- Advanced
- Lesson 50/68
- 4 min
Learn multi-service with docker-compose.
docker-compose
Compose defines several containers in one YAML file and starts them together. A Go service and a database:
services:
api:
build: .
ports: ["8080:8080"]
environment:
DATABASE_URL: postgres://app:gizli@db:5432/app?sslmode=disable
depends_on: [db]
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: gizlidocker compose up starts both on the same network; the service reaches the database by the name db.
depends_on and readiness
depends_on only sets the start order; it doesn't guarantee the database is ready to accept connections. Either use healthcheck + condition: service_healthy or retry Ping on the Go side:
for i := 0; i < 10; i++ {
if err = db.Ping(); err == nil {
break
}
time.Sleep(time.Second)
}Practice Retry
Write retry(n int, f func() error) error: try f at most n times, return nil on success and the last error otherwise. Test it with a function that succeeds on the third try and print the number of attempts.
Starter code
package main
import (
"errors"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"errors"
"fmt"
)
func retry(n int, f func() error) error {
var err error
for i := 0; i < n; i++ {
if err = f(); err == nil {
return nil
}
}
return err
}
func main() {
deneme := 0
err := retry(5, func() error {
deneme++
if deneme < 3 {
return errors.New("hazır değil")
}
return nil
})
fmt.Println(deneme, err)
}Expected output
3 <nil>
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which address does the api container use to reach the database?
- localhost:5432
- 127.0.0.1:5432
- postgres.local:5432
- db:5432 Correct answer
Explanation: Compose turns service names into DNS names on the network; inside a container, localhost is the container itself.
2 Port mapping
services:
api:
build: .
____: ["8080:8080"]
services:
api:
build: .
ports: ["8080:8080"]
Explanation: ports forwards a host port to the container's port.
3 Compose keys
| Term | Meaning |
|---|---|
build |
Image from a Dockerfile |
image |
Ready-made image |
environment |
Environment variables |
depends_on |
Start order |