Can docker-compose share an ip between services with discrete ports?

空扰寡人 提交于 2019-12-11 15:49:31

问题


We currently have docker containers with complex builds using supervisord so that we can group services together. For example, nginx and ssh.

I'm attempting to rebuild these with more service-driven isolation linked by shared volumes. However, without mapping the IP to the host, I can't seem to find a way to allow IP addresses to be shared even though the ports may be discrete.

What I'm trying to do is something like this:

version: '2'
services:
  web:
    image: nginx
    volumes:
    - /data/web:/var/www
    networks:
      public:
        ipv4_address: 10.0.0.1
    ports:
    - "10.0.0.1:80:80"
  ssh:
    image: alpine-sshd
    volumes:
    - /data/web:/var/www
    networks:
      public:
        ipv4_address: 10.0.0.1
    ports:
    - "10.0.0.1:22:22"
networks:
  public:
    external: true

...where public is a predefined docker macvlan network.

When I try this, I get the error:

ERROR: for ssh  Cannot start service ssh: Address already in use

I'm aware that another solution to this is to introduce a third service to work as a proxy. However, I thought this would be a simple enough case not to need it.

Is it possible to configure docker-compose/docker-networking to route by the port to allow the same IP address to be used for different containers?


回答1:


Is it possible to configure docker-compose/docker-networking to route by the port to allow the same IP address to be used for different containers?

Yes we can(familiar? -_-!). There is an option of network mode presented by Docker, called service:service-name.

When we execute docker run, we could add --network=service:service-name flag. It means that current container uses the same network namespace of service:service-name. More information reference here.

Try the following compose file below. I've tested it, which works well.

version: '2'
services:
  web:
    image: nginx
    networks:
      public:
        ipv4_address: 10.0.0.2
    ports:
      - "8880:80"
      - "2220:22"

  ssh:
    image: panubo/sshd
    network_mode: "service:web"
    depends_on:
      - web
networks:
  public:
    external: true


来源:https://stackoverflow.com/questions/52688218/can-docker-compose-share-an-ip-between-services-with-discrete-ports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!