'`docker compose up --build` not recreating container

When making changes to something that affects an image that a service uses, running docker compose up --build should rebuild that image and then recreate the corresponding service's container so that it uses the new image.

If there are existing containers for a service, and the service’s configuration or image was changed after the container’s creation, docker-compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes). To prevent Compose from picking up changes, use the --no-recreate flag. See https://docs.docker.com/compose/reference/up/.

I've noticed recently that this is not the case, i.e. if I make a change to a dependency of an image, docker compose up --build will rebuild the image (as expected), but will not recreate the container. docker image ls -a shows both the old and new images, but docker compose images shows that the old images is still being used.

Versions

$ docker --version
Docker version 20.10.12, build e91ed5707e
$ docker compose version
Docker Compose version 2.3.3

Recreate the issue

Minimal files

compose.yaml

version: "3.7"

services:
  a:
    build:
      context: .

Dockerfile

FROM python:3.8-slim

COPY main.py ./main.py
CMD python main.py

main.py

print("1")

Steps

  • docker compose up --build
  • docker compose images
    • note the Image Id
  • modify main.py
    • change print('1') to print('2')
  • docker compose up --build
    • a new image will be created because a dependency (main.py) has changed
    • however the old code in main.py executes
  • docker compose images
    • the old Image Id is still listed
  • docker compose up --build --force-recreate
    • the modified code in main.py executes
  • docker compose images
    • the new Image Id is now listed


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source