Gaurang Shah
Gaurang Shah

Reputation: 12930

docker-compose connecting to other container fails

I have two docker images, one rest server (flaskapp) and another web server (web). I am trying to run them using docker-compose.

However, it seems that the web container is not able to contact the rest container

Following is my docker-compose.yml file:

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:

http://flaskapp:5001/todos

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.

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.

I don't want to expose my rest server to host machine.

Upvotes: 4

Views: 12577

Answers (2)

veben
veben

Reputation: 22332

You need to:

  1. define a common network for your containers
  2. expose the port 5001 of your flaskapp container

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". 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

Upvotes: 3

HelloThere
HelloThere

Reputation: 1060

just add:

expose:
 - "5001"

to flaskapp section.

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.

Upvotes: 1

Related Questions