Adding default external network in docker-compose

Viewed 7094

I am trying to learn docker and understanding docker-compose

As I was trying out the external network section:

 networks:
  default:
    external:
      name: my-pre-existing-network

I understand that 'my-pre-existing-network' needs to be created.

Is it possible to create a new default external network from within the compose file itself?

This is more from a learning/understanding perspective And also alternative to the docker network create command. Thanks.

3 Answers

In case you create a network within your compose-file then that one is not considered to be "external". You can create a custom network using network section:

version: '3'

services:
    my-service:
    # can be a pre-built image like this or built locally (check reference)
        image: some-image:latest 
        networks:
            - custom-network

networks:
    custom-network:
        driver: bridge

If you are going to use your compose file with swarm, you might want to choose driver: overlay. Additional information can be found here.

Ref. the "use a pre-existing network" documentation: "Instead of attempting to create a network called [projectname]_default, Compose looks for a network called my-pre-existing-network and connect your app’s containers to it." - docker-compose will not attempt to create the network.

The external network must already exist (e.g. "my-pre-existing-network"), it could be a docker network created from a different docker-compose environment or a docker network created using the docker network create command.

Note: docker-compose networks are prefixed with COMPOSE_PROJECT_NAME. You can use docker network ls to list existing networks.

Maybe someone still looking for answer. Probably this will work.

version: '3.8'
services:
  api:
    networks:
      - test

networks:
   test:
    driver: bridge
    external: true
Related