docker-compose: difference between network and link

前端 未结 1 526
野性不改
野性不改 2020-12-02 20:00

I\'m learning docker. I see those two terms make me confuse. For example here is a docker-compose that defined two services redis and web-app.

相关标签:
1条回答
  • 2020-12-02 20:24

    Links have been replaced by networks. Docker describes them as a legacy feature that you should avoid using. You can safely remove the link and the two containers will be able to refer to each other by their service name (or container_name).

    With compose, links do have a side effect of creating an implied dependency. You should replace this with a more explicit depends_on section so that the app doesn't attempt to run without or before redis starts.

    As an aside, I'm not a fan of hard coding container_name unless you are certain that this is the only container that will exist with that name on the host and you need to refer to it from the docker cli by name. Without the container name, docker-compose will give it a less intuitive name, but it will also give it an alias of redis on the network, which is exactly what you need for container to container networking. So the end result with these suggestions is:

    version: '2'
    # do not forget the version line, this file syntax is invalid without it
    
    services:
      redis:
        image: redis:latest
        ports:
          - "6379:6379"
        networks:
          - lognet
    
      app:
        container_name: web-app
        build:
          context: .
          dockerfile: Dockerfile
        ports:
          - "3000:3000"
        volumes:
          - ".:/webapp"
        depends_on:
          - redis
        networks:
          - lognet
    
    networks:
      lognet:
        driver: bridge
    
    0 讨论(0)
提交回复
热议问题