Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom network for docker compose via command line

Tags:

docker

Really basic one but this documentation only seems to mention the docker-compose file itself as opposed to the command line: https://docs.docker.com/compose/networking/#links

When I call:

docker-compose up -d service1 service2

I want those created containers to be on a new network with a custom name. How do I specify this network when using the docker-compose up command?

Even if I add network config to the docker-compose file:

networks:
  mynetwork:

service1:
  networks:
    - mynetwork

The docker-compose command still creates the containers on a default network, rather than use "mynetwork".

like image 343
FBryant87 Avatar asked Sep 05 '25 09:09

FBryant87


1 Answers

  1. Create a external network if it doesn't exist -

    $ docker network create mynetwork || true
    
  2. Define external network to compose file -

    .........
       ports:
         - "8088:8088"
       networks:
         - mynetwork
    
     networks:
       mynetwork:
         external: true
    

Similarly, you can also use the default network create by compose but it will prefix your current directory name to the network name defined. You can also use the host network mode but that's not suggested.

Above two use cases are old now, since compose 3.5 you can give custom names to your compose environment. This lets services in multiple compose files talk to each other without doing much of a configuration.

Preferred

  • Recently in docker compsoe 3.5, they launched custom name feature. So in case you can use compose 3.5, you can opt for giving a custom name to your docker compose network. Compose will create a new network in case it doesn't exist.(preferred) https://docs.docker.com/compose/compose-file/#name-1

Ex -

    version: '3.5'
    .........
       ports:
         - "8088:8088"
       networks:
         - mynetwork

       networks:
         mynetwork:
           external: true
           name: mynetwork
like image 67
vivekyad4v Avatar answered Sep 09 '25 01:09

vivekyad4v