Q:

How to automatically restart a container if another container is recreated in docker-compose?

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?

A:

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?

