4

I have two containers: A and B. Container B needs to be restarted each time container A is recreated to pick up that container's new id.

How can this be accomplished without hackery?

1 Answer 1

4

Not something I've tried to do before, but .. the docker daemon emits events when certain things happen. You can see some of these at https://docs.docker.com/engine/reference/commandline/events/#parent-command but, for example:

Docker containers report the following events:

attach commit copy create destroy detach die exec_create exec_detach exec_start export health_status kill oom pause rename resize restart start stop top unpause update

By default, on a single docker host, you can talk to the daemon through a unix socket /var/run/docker.sock. You can also bind that unix socket into a container so that you can catch events from inside a container. Here's a simple docker-compose.yml that does this:

version: '3.2'

services:

  container_a:
    image: nginx
    container_name: container_a

  container_b:
    image: docker
    container_name: container_b
    command: docker events
    restart: always
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

Start this stack with docker-compose up -d. Then, in one terminal, run docker logs -f container_b. In another terminal, run docker restart container_a and you'll see some events in the log window that show the container restarting. Your application can catch those events using a docker client library and then either terminate itself and wait to be restarted, or somehow otherwise arrange restart or reconfiguration.

Note that these events will actually tell you the new container's ID, so maybe you don't even need to restart?

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, very useful. I actually ended up creating a HEALTHCHECK for container B in my example. The state changes from healthy to unhealthy when container A is recreated (based on some bash logic) that returns exit code 1, and is automatically restarted by autoheal github.com/willfarrell/docker-autoheal
awesome, healthcheck sounds like a nice approach, glad it helped :)
@relik could you post an answer containing your healthcheck bash script? It would be really helpful to me & others :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.