Docker错误转发端口

时间:2019-01-02 22:50:12

标签: docker routing docker-compose compose jwilder-nginx-proxy

我有几个域共享一个公共IP(EC2实例)。我的设置是这样的:

/home/ubuntu包含docker-compose.yml

version: '3'
services:
  nginx-proxy:
    image: "jwilder/nginx-proxy"
    container_name: nginx-proxy
    volumes:
    - /var/run/docker.sock:/tmp/docker.sock:ro
    ports:
    - "80:80"
    restart: "always"

这将创建一个名为ubuntu_default的网络,该网络将允许其他撰写实例加入。 nginx-proxy图像会为其他组合实例创建反向代理,以便您可以访问example.com并被路由到适当的组合实例中的适当的UI。

/home/ubuntu/example.com/project-1包含一个docker-compose.yml,例如:

version: '3'
services:
  db:
    build: "./db"   # mongo
    volumes:
    - "./data:/data/db"
    restart: "always"
  api:
    build: "./api"   # a node backend
    ports:
    - "9005:9005"
    restart: "always"
    depends_on:
      - db
  ui:
    build: "./ui"   # a react front end
    ports:
    - "8005:8005"
    restart: "always"
    environment:
    - VIRTUAL_HOST=project-1.example.com   # this tells nginx-proxy which domain to proxy
    - VIRTUAL_PORT=8005  # this tells nginx-proxy which port to proxy
networks:
  default:
    external:
      name: ubuntu_default

/home/ubuntu/testing.com/project-2包含一个docker-compose.yml,例如:

version: '3'
services:
  db:
    build: "./db"  # postgres
    volumes:
    - "./data:/var/lib/postgresql/data"
    restart: "always"
  api:
    build: "./api"  # a python backend
    ports:
    - "9000:9000"
    restart: "always"
    depends_on:
      - db
  ui:
    build: "./ui"  # a react front end
    ports:
    - "8000:8000"
    restart: "always"
    environment:
    - VIRTUAL_HOST=testing.com,www.testing.com # tells nginx-proxy which domains to proxy
    - VIRTUAL_PORT=8000 # tells nginx-proxy which port to proxy
networks:
  default:
    external:
      name: ubuntu_default

所以基本上:

  • project-1.example.com:80转发到在:8005上运行的UI
  • project-1.example.com:80/api转发到运行在:9005上的API
  • testing.com转到运行在:8000上的UI
  • testing.com/api转发到运行在:9000上的API

...而且只要我一次只运行一个,一切都可以完美运行。当我启动两个Compose实例时,/ api url开始冲突。我可以坐在其中之一上并反复刷新,有时会在example.com/api中看到一个,有时会在testing.com/api中看到一个。

我现在不知道发生了什么。也许我要应对的前提存在根本缺陷,但似乎是Docker / Compose的预期用途。我乐于接受建议,否则可以实现相同的目的。

1 个答案:

答案 0 :(得分:1)

Docker容器在其网络上使用DNS查找进行通信。如果多个容器在同一网络上具有相同的别名,则它将在具有每个网络连接的容器之间循环负载均衡。如果您不希望容器彼此通信,那么您不希望它们在同一个docker网络上。好消息是,您可以使用多个网络来解决此问题,而不是将api和db服务器放在前端代理网络上:

version: '3'
services:
  db:
    build: "./db"  # postgres
    volumes:
    - "./data:/var/lib/postgresql/data"
    restart: "always"
  api:
    build: "./api"  # a python backend
    ports:
    - "9000:9000"
    restart: "always"
    depends_on:
      - db
  ui:
    build: "./ui"  # a react front end
    ports:
    - "8000:8000"
    restart: "always"
    networks:
    - default
    - proxy
    environment:
    - VIRTUAL_HOST=testing.com,www.testing.com # tells nginx-proxy which domains to proxy
    - VIRTUAL_PORT=8000 # tells nginx-proxy which port to proxy
networks:
  proxy:
    external:
      name: ubuntu_default

如果您不覆盖默认网络,则docker将为您的撰写项目创建一个,并将其用于未分配给另一个网络的任何容器。