Home > Software engineering >  Docker compose: Cannot access Flask from localhost
Docker compose: Cannot access Flask from localhost

Time:10-14

I am trying to access Flask app from the Docker compose getting started tutorial from my local host but without making changes to this pruned Dockerfile:

# syntax=docker/dockerfile:1
FROM python:3.9-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt

This if my docker-compose.yml:

    version: "3.9"

services:
  web:
    build: .
    command: flask run
    volumes: 
      - type: bind
        source: .
        target: /code 
    environment:
      - ENV FLASK_APP=app.py
        ENV FLASK_RUN_HOST=0.0.0.0
    ports:
      - target: 5000
        published: 8000      
    networks:
      - counter-net
  redis:
    image: "redis:alpine"
    networks:
      - counter-net
      
networks:
  counter-net:
  
volumes:
  volume-net:

When I use docker compose up I can see: Running on http://127.0.0.1:5000 but I cannot access it on Running on 127.0.0.1:8000 or localhost:8000

I can see 2_counter-net when I list networks and if relevant earlier I tried creating a volume but removed this when I changed the source to . and it came up without error.

How can I correct my config please?

CodePudding user response:

You are trying to use a bridge network so that ports opened in the container can be forwarded to ports on your host computer. It's true that you could remove the user-defined network and just rely on the default bridge network (by removing all the "networks" sections from the YAML file). That should solve your problem. However, Docker doesn't recommend this approach for production.

The other option is to add a bridge driver to your user-defined network specification:

networks:
  counter-net:
    driver: bridge

And David is right, you should fix the YAML in your environment.

    environment:
      - FLASK_APP=app.py
      - FLASK_RUN_HOST=0.0.0.0
  • Related