Search code examples
dockerdocker-composedocker-network

Docker Compose networks: create if not exists across multiple files and service definitions?


Docker Compose here. I'm looking at the Docker networking guide and trying to understand how to perform the equivalent of a "CREATE TABLE IF NOT EXISTS" with a Docker network. Meaning, in SQL, you can usually tell the RDBMS to create a table if it doesn't already exist.

Here, from inside a Docker Compose file, I want to tell Docker to create a network if it doesn't already exist, and then connect my services (containers) to it.

Is this possible to do? Ideally it could be flexible such that I could have several different Docker Compose files (docker-compose-a.yml, docker-compose-b.yml and docker-compose-c.yml), and all of them defined various services (containers), but all of them were configured to create (unless already created previously) and use the same "fizzbuzz" network.

Any ideas?


Solution

  • There's no way at the moment to create network if does not exist.

    You can read more here.

    Update 1

    As you said in comments, you can add this to your docker-compose files (each one) in order to be in the same network.

    First of all create a network by this command:

    docker network create NAME
    

    Then add this to docker-compose files:

    // from here to next comment is your docker-compose current status
    version: '3'
    
    services:
      web:
        image: some
    // end here your current
    // here is the part you should add for network
    networks:
      default:
        external:
          name: NAME
    

    Note that before running docker-compose up -d, you should create the network or you'll get network does not exist error.