Search code examples
docker-composecontainersdockerfiledocker-network

Create Docker Network in docker-compose.yml or dockerfile


My docker services require a network to work properly. I intend to share my compose file, but I don't want to manually create the network with the right parameters each time.

I would like the network to be created during the build process, in the Dockerfile or in the docker-compose file.


Solution

  • I don't think you can create a network in your Dockerfile, but you can do so in your docker-compose.yml file.

    Have you looked at networking in Docker Compose?

    You can specify your own networks with the networks key in your docker-compose.yml file. This lets you create custom networks and specify custom network drivers and options.

    Each service in your docker-compose.yml file can specify what networks to connect to, with the service level networks key.

    Here is an example from the Compose docs

    version: "3"
    services:
      proxy:
        build: ./proxy
        networks:
          - frontend
      app:
        build: ./app
        networks:
          - frontend
          - backend
      db:
        image: postgres
        networks:
          - backend
    
    networks:
      frontend:
        # Use a custom driver
        driver: custom-driver-1
      backend:
        # Use a custom driver which takes special options
        driver: custom-driver-2
        driver_opts:
          foo: "1"
          bar: "2"