代码之家  ›  专栏  ›  技术社区  ›  Benyamin Jafari

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

  •  3
  • Benyamin Jafari  · 技术社区  · 6 年前

    我有一个容器,它有几个端口,我想访问它的一个端口( 9001 )在这个码头的外面。

    • 我的Docker IP是: 172.17.0.1
    • 我的容器IP是: 172.19.0.23
    • 我的服务器IP是: 192.168.1.131

    我已经查过了,我发现 expose port 关键字,我做到了,但没有成功。

    如何暴露Docker端口以使容器可从外部访问
    Reference


    这是我的Docker撰写文件:

    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"
    

    我在Docker上用以下代码编写文件: $ docker-compose up -d

    • 但是当我使用 server_IP:9001 --> 192.168.1.131:9001 docker_IP:9001 --> 172.17.0.1:9001 无法访问(在远程或本地模式下)
    • 但使用时 container_IP:9001 --> 172.19.0.23:9001 这 在当地工作。

    我该怎么做才能接触到 服务器IP:9001-->192.168.1.131:9001 是吗?


    [ 注意 ]以下内容:

    • createDB.sh 运行多个操作,如创建 ZMQ开启 第9001页 港口 .

    • 我已经设置了允许的端口,使用 $ ufw allow 9001

    • 我试过Ubuntu 16.04和Ubuntu服务器16.04

    任何帮助都将不胜感激。

    2 回复  |  直到 6 年前
        1
  •  1
  •   g3org3    6 年前

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

        2
  •  0
  •   Benyamin Jafari    6 年前

    ivms

    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.
    

    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"