Mike
Mike

Reputation: 477

Docker-compose: Start container after another with timeout

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"

Upvotes: 8

Views: 18062

Answers (1)

ErikMD
ErikMD

Reputation: 14743

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"

Upvotes: 8

Related Questions