Rebuild containers using docker compose when dockerfile changes

When using Docker Compose, by default, it leverages cached images to speed up container builds. This means that if you make changes to your Dockerfile or the build context, Docker Compose may not rebuild the containers since it assumes that the existing cached images are still valid.

However, in some cases, you may want to force Docker Compose to rebuild all containers, even if the images haven't changed. This could be necessary if you have made changes to the Dockerfile or build context that affect the container's behavior or dependencies.

Rebuild the containers

There are two ways to force Docker Compose to rebuild containers when the Dockerfile changes:

Use the --force-recreate flag

We can use the --force-recreate flag with the docker-compose up command.  This flag tells Docker Compose to recreate all containers, regardless of whether the images have changed or not. It ensures that any modifications made to the Dockerfile or build context are applied and that the containers are rebuilt from scratch.

Here's how you can do it:

  1. Open a terminal or command prompt.

  2. Navigate to the directory where your docker-compose.yml file is located.

  3. Run the following command:

docker-compose up --force-recreate
Command to use the --force-recreate flag

Note: The --force-recreate flag will also rebuild containers that haven't changed. This can be useful if you want to make sure that all of your containers are up-to-date.

Use the docker-compose build

Alternatively, we can use the docker-compose build command to rebuild the images, and then use the docker-compose up command to start the containers. This command starts the containers defined in your docker-compose.yml file and forces Docker Compose to rebuild any service that has a modified Dockerfile or build context.

Here's how you can do it:

  1. Open a terminal or command prompt.

  2. Navigate to the directory where your docker-compose.yml file is located.

  3. Run the following commands:

docker-compose build
docker-compose up
Command to use the docker-compose build
  • The docker-compose build command will only rebuild the images that have changed. This can save time if you only make changes to a few files in the Dockerfile.

If the containers are already running, you can stop them first by using the command:

docker-compose down
Command to stop docker containers

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved