如何使用 docker-compose 在 docker/container 之外公开容器端口?

How to expose a container port outside of docker/container using docker-compose?

我有一个容器,它有多个端口,我想以远程方式访问此 docker 之外的其中一个端口 (9001)。


我已经搜索过了,我找到了 expose port 关键字,我做了但没有成功。

How to expose docker ports to make your containers externally accessible
Reference


这是我的 docker-compose 文件:

version: '3'

services:
  nginx:
      image: nginx:latest
      container_name: nginx
      ports:
        - "8010:8010"

      volumes:
        - .:/code
        - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

      links:
        - ivms

      restart: unless-stopped

  ivms:
      build: .
      container_name: ivms
      command: bash bashes/createDB.sh
      volumes:
        - .:/code
      expose:
        - "8010"
        - "9001"  # exposed disired port
      ports:
        - "9001:9001"

I 运行 以上 docker-撰写文件:$ docker-compose up -d

我应该怎么做才能访问server_IP:9001 --> 192.168.1.131:9001?


[注意]:


如有任何帮助,我们将不胜感激。

如果你想实际映射你应该使用的端口

ivms:
  build: .
  container_name: ivms
  command: bash bashes/createDB.sh
  volumes:
    - .:/code
  ports:
    - "8010:8010"
    - "9001:9001"  # now you can access them locally

警告您正在为这两个服务 ivms 和 nginx 使用相同的端口

The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.

The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. -Docker Docs

问题已通过以下说明解决:

在 ZMQ 应用程序中(在 ivms 容器中)我使用服务器 IP 绑定连接如下:

import zmq

if __name__ == '__main__':
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.setsockopt(zmq.SUBSCRIBE, "")
    socket.bind("tcp://192.168.1.131:9001")  # doesn't work with server or docker IP

    while True:
        data = socket.recv_json()

它只工作如下:

socket.bind("tcp://192.168.1.131:9001")  # works, but can't access as remote

现在我将这一行编辑如下:

socket.bind("tcp://*:9001")  # Works both locally and remotely.

这是我的 docker-compose.yml 配置:

version: '3'

services:
  nginx:
      image: nginx:latest
      container_name: nginx
      ports:
        - "8010:8010"

      volumes:
        - .:/code
        - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

      links:
        - ivms

      restart: unless-stopped

  ivms:
      build: .
      container_name: ivms
      command: bash bashes/createDB.sh
      volumes:
        - .:/code
      expose:
        - "8010"
      ports:
        - "9001:9001"