docker-composedocker-volume

How to return one container to a clean state in docker compose?


Using docker-compose restart <service> retains some persistent state of the container (e.g. it does not remove database tables from the postgres alpine container, presumably because a persistent volume is defined somewhere inside of that image, even without being mentioned in docker-compose.yaml).

Using e.g. docker-compose down && docker-compose up -d returns all containers to a fresh state.

How do you return just one container to a fresh state?


Solution

  • To recreate fresh a single service with docker-compose:

    docker-compose rm -svf <service> && docker-compose up -d <service>
    

    When you remove the container, the -v instructs to also evict from storage any anonymous volumes that were attached to it. If you omit this -v then you will accumulate unused volumes, and subsequently want to run docker volume prune to clean those up. The -s is just a shortcut instead of typing docker-compose stop <service> beforehand, and -f avoids prompting to confirm yes.

    For comparison, if you merely attempt docker-compose restart <service> then any existing anonymous volumes will be maintained (i.e. the process will be rebooted but internal stored state of the container can persist). Supposedly docker-compose build <service> && docker-compose restart <service> would work if there had been any changes in the source for that container.

    A more concise alternative is:

    docker-compose up -V -d <service>

    This does recreates a particular service, even if the services were already up; the -V (which can also be expressed as --renew-anon-volumes) means to create fresh anonymous volumes instead of retrieving those from the pre-existing container. However it leaves the previous volumes stored until subsequent pruning.