When working with Docker Compose, sometimes you need to rebuild a container because you’ve changed your Dockerfile, source code, or configuration.
Simply running docker-compose up may not rebuild the image unless explicitly told to.
1️⃣ Why Rebuilding Is Necessary
- You updated the Dockerfile
- Dependencies changed (e.g.,
requirements.txt,package.json) - Base image was updated
- Configuration or environment changes
If you don’t rebuild, Docker may keep using the cached image.
2️⃣ The Rebuild Commands
Option 1 — Rebuild and Restart
docker-compose up --build
This:
- Forces a rebuild of images
- Starts (or restarts) containers using the new image
Option 2 — Rebuild Without Starting
docker-compose build
Only builds images without starting containers.
Option 3 — Force No Cache
If you want a completely fresh build:
docker-compose build --no-cache
This ignores cached layers.
Option 4 — Rebuild a Specific Service
If your docker-compose.yml has multiple services:
docker-compose build <service_name>
docker-compose up <service_name>
3️⃣ Full Rebuild and Cleanup
If you want to start completely fresh:
docker-compose down --rmi all --volumes --remove-orphans
docker-compose up --build
This:
- Stops containers
- Removes all images used by the services
- Deletes volumes and orphan containers
- Rebuilds everything
4️⃣ Common Mistakes
| Mistake | Why It Happens | Solution |
|---|---|---|
| Changes not showing | Old image is still cached | Use --build or --no-cache |
| Wrong container still running | Didn’t restart after build | Run docker-compose up --build |
| Persistent data issues | Old volume still attached | Use docker-compose down -v |
📌 Summary
To rebuild containers in Docker Compose:
| Action | Command |
|---|---|
| Rebuild & start | docker-compose up --build |
| Rebuild only | docker-compose build |
| Rebuild without cache | docker-compose build --no-cache |
| Specific service rebuild | docker-compose build <service> |