Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker compose: Cannot access Flask from localhost

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?

like image 390
saltyeggs Avatar asked Aug 13 '26 20:08

saltyeggs


1 Answers

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
like image 132
Nick K9 Avatar answered Aug 16 '26 11:08

Nick K9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!