Home > Back-end >  Dockerized flask web app throws 403 Forbidden
Dockerized flask web app throws 403 Forbidden

Time:03-08

I have a basic REST API implemented in Flask. I want to try using Docker to containerize it. I'm completely new to Docker, but based on what I was able to figure out on various forums, this is what I have set up.

Dockerfile

FROM python:3.8-alpine

WORKDIR /myapplication

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .
ENV FLASK_APP="app.py"

CMD ["python3", "-m" , "flask", "run"]

requirements.txt

Flask==2.0.2

I then go to the Terminal, and run $ docker build -t myapp:latest .

The build is successful, and I can see my app listed in the Docker Desktop app

I then run

$ docker run --rm -it -p 8080:8080 myapp:latest

 * Serving Flask app 'app.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)

Docker Desktop shows myapp is in use.

So far, so good. But this is where I start running into issues.

I am also using Postman for API route testing. If I were to run the application outside of Docker, and I go to 127.0.0.1:5000/data or any of my other routes, I get a response just fine. But with the Docker build running, I am no longer able to access this route, or any other route.

I have tried endless combinations: 127.0.0.1:5000, 127.0.0.1:8080, localhost, localhost:5000, localhost:8080, to no avail.

The only one that gives me ANY response is 127.0.0.1:5000. The response I do get is a 403 Forbidden, with Postman saying "The request was a legal request, but the server is refusing to respond to it."

For what its worth, I am running this on a new M1 Pro MacBook. I know the new Macs are touchy with permissioning, so I wouldn't be surprised if permissions were the issue.

I really don't know what to do or where to go from here, every source I've tried has given me a slight variation on what I have already attempted, and I'm no closer to getting this to work. Please help, thanks.

CodePudding user response:

In dockerfile you need to expose your port

...
ENV FLASK_APP="app.py"
EXPOSE 5000
CMD ["python3", "-m" , "flask", "run"]

CodePudding user response:

your docker application is running on port 5000 inside the container, but in your docker run command you are binding port 8080 with port 8080 inside the container which should be 5000 instead. As there is nothing running on port 8080 inside the container hence you are getting the 403 error

the command should be

docker run --rm -it -p 8080:5000 myapp:latest

from host machine you can access the app on port 8080, i.e:

127.0.0.1:8080/data # access from host machine

127.0.0.1:5000/data # access from inside container

  • Related