简体   繁体   English

docker-compose连接到其他容器失败

[英]docker-compose connecting to other container fails

I have two docker images, one rest server ( flaskapp ) and another web server ( web ). 我有两个flaskapp镜像,一个休息服务器( flaskapp )和另一个Web服务器( web )。 I am trying to run them using docker-compose . 我正在尝试使用docker-compose运行它们。

However, it seems that the web container is not able to contact the rest container 但是,似乎Web容器无法与其余容器联系

Following is my docker-compose.yml file: 以下是我docker-compose.yml文件:

version: '3'
services:
  flaskapp:
    build: ./rest_server
    restart: always
    networks:
      - docker_network
    expose:
      - 5001

  web:
    build: ./web
    restart: always
    ports:
      - 3002:3000
    depends_on:
      - flaskapp
    networks:
      - docker_network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://flaskapp:5001/todos"]
networks:
  docker_network:
    driver: bridge

My web application refers to the following URL: 我的Web应用程序引用以下URL:

http://flaskapp:5001/todos HTTP:// flaskapp:5001 /待办事项

However, If I log to docker container using docker exec -it <id> /bin/bash and run the following command I get the json response I expect. 但是,如果我使用docker exec -it <id> /bin/bash登录到docker容器并运行以下命令,我会得到我期望的json响应。

curl http://flaskapp:5001/todos curl http:// flaskapp:5001 / todos

I can expose my rest server port as well, and then change the rest server address to localhost in web server and this will resolve the issue, however this is not what I would like. 我也可以暴露我的休息服务器端口,然后将其余服务器地址更改为Web服务器中的localhost,这将解决问题,但这不是我想要的。

I don't want to expose my rest server to host machine. 我不想将我的休息服务器暴露给主机。

You need to: 你需要:

  1. define a common network for your containers 为容器定义一个通用网络
  2. expose the port 5001 of your flaskapp container 暴露您的flaskapp容器的端口5001

Indeed, according to the documentation , the EXPOSE instruction "exposes ports without publishing them to the host machine - they'll only be accessible to linked services". 实际上,根据文档EXPOSE指令“暴露端口而不将它们发布到主机 - 它们只能被链接服务访问”。 So it allows communication between the container which "expose" the port, and other containers in the same network. 因此,它允许“暴露”端口的容器与同一网络中的其他容器之间的通信。

Try something like that: 尝试类似的东西:

version: '3'
services:
    flaskapp:
        build: ./rest_server
        expose:
            - 5001
        networks:
            - docker_network

    web:
        build: ./web
        restart: always
        ports:
            - 3002:3000
        networks:
            - docker_network
        depends_on:
            - flaskapp

networks:
  docker_network:
    driver: bridge

just add: 只需添加:

expose:
 - "5001"

to flaskapp section. 到flaskapp部分。

This doesn't expose the port: 5001 to the host, this simply exposes port 5001 to all the containers in the same network, which is what you want. 这不会将端口:5001暴露给主机,这只是将端口5001暴露给同一网络中的所有容器,这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM