Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker-Compose: How to depends_on a container on another network? I am getting an error saying container 'undefined' even though networks are linked

I have 2 different services in 2 distinct docker-compose.yml files in 2 different locations.

Service 1: wordpress

version: "3.7"

services:

  # Wordpress
  wordpress:
    depends_on:
      - db
    container_name: wordpress
    image: wordpress:latest
    ports:
      - '8000:80'
    restart: unless-stopped
    volumes: ['./:/var/www/html']
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
    networks:
      - wpsite
networks:
  wpsite:
    driver: bridge

Service 2: frontend

version: "3.7"

services:
  frontend:
    depends_on:
      - wordpress
    container_name: frontend
    restart: unless-stopped
    stdin_open: true
    build:
      context: ../realm-frontend
    volumes:
      - static:/realm-frontend/build
    networks:
      - cms_wpsite

networks:
  cms_wpsite:
    external: true

I have a shell script that goes to the 2 locations and runs the docker-compose files to create the containers.

Script

cd ~/cms;
docker-compose -f docker-compose.yml up -d --build --force-recreate

cd ../frontend;
docker-compose -f docker-compose.yml up -d --build --force-recreate

As you can see I have created the link between the networks using bridge.

When I docker network inspect {network id} I can see both the containers wordpress and frontend are in the network. However, when the second container is created with the depends_on command, I get the following error.

ERROR: Service 'frontend' depends on service 'wordpress' which is undefined.

I am not sure why this is, given that they're in the same network.

I'd appreciate any help. Thanks!

like image 250
Rahul Avatar asked Dec 31 '22 20:12

Rahul


1 Answers

Depends_on only works on services within the same compose file, so to do what you want, you would need to use something like wait-for-it.sh. Take a look here for more information: https://docs.docker.com/compose/startup-order/

Something like this may work for you or you can create a custom wait-for-it script as well:

services:
  frontend:
    container_name: frontend
    restart: unless-stopped
    stdin_open: true
    build:
      context: ../realm-frontend
    volumes:
      - static:/realm-frontend/build
    command: ["./wait-for-it.sh", "wordpress:80", "--", "yourfrontendcmd"]
    networks:
      - cms_wpsite
like image 123
Carlos Avatar answered Jan 02 '23 08:01

Carlos