5

Is it possible to start myapp-1 with myapp-2, then sleep for 30 seconds and only then start myapp-3?

Tried this docker-compose.yml with no luck.

version: '3'
services:
  myapp-1:
    container_name: myapp-1
    image: myapp:latest
    restart: always
  myapp-2:
    container_name: myapp-2
    image: myapp:latest
    restart: always
  test-sleep:
    image: busybox
    command: ["/bin/sleep", "30"]
    depends_on:
      - "myapp-1"
      - "myapp-2"
  myapp-3:
    container_name: myapp-3
    image: myapp:latest
    restart: always
    depends_on:
      - "test-sleep"
Mike
  • 347
  • 1
  • 2
  • 15
  • You can't directly do this in Compose; is there a specific reason you want to? (You can't wait for a container to exit, or wait for it to be "really running".) [Docker Compose wait for container X before starting Y](https://stackoverflow.com/questions/31746182/docker-compose-wait-for-container-x-before-starting-y) discusses the broader problem of waiting for a dependent container to be ready. – David Maze Aug 24 '20 at 12:56
  • **See Also**: [Docker Compose wait for container X before starting Y](https://stackoverflow.com/q/31746182/1366033) – KyleMit Nov 19 '20 at 23:14

1 Answers1

7

The docker-compose.yml you proposed could not address your use case, as the depends_on property does not wait for the dependencies to be ready (or terminated), but only for them to be started (i.e., in your example, myapp-3 is started as soon as the /bin/sleep 30 command has been started).

See e.g. the corresponding doc:

depends_on does not wait for [dependencies] to be “ready” before starting [the service] - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

The link above mentions several tools (including wait-for-it) that could be used to wait that some service dependencies are ready (provided they expose a web service at a given TCP port).

Otherwise, if you just want to wait for 30s before starting myapp-3, assuming the Dockerfile of myapp-3 contains CMD ["/prog", "first argument"], you could just get rid of test-sleep and write something like:

version: '3'
services:
  myapp-1:
    container_name: myapp-1
    image: myapp:latest
    restart: always
  myapp-2:
    container_name: myapp-2
    image: myapp:latest
    restart: always
  myapp-3:
    container_name: myapp-3
    image: myapp:latest
    restart: always
    command:
      - '/bin/sh'
      - '-c'
      - '/bin/sleep 30 && /prog "first argument"'
    depends_on:
      - "myapp-1"
      - "myapp-2"
ErikMD
  • 13,377
  • 3
  • 35
  • 71