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.
3
Answers
This ended up working, thank you @Tasnuva
Dockerfile, append CMD with
--host
In the CLI,
$ docker run --rm -it -p 8080:5000 myapp:latest
Accessing endpoints in Postman at
127.0.0.1:8080
In dockerfile you need to expose your port
your docker application is running on port
5000
inside the container, but in your dockerrun
command you are bindingport
8080 with port8080
inside the container which should be5000
instead. As there is nothing running on port8080
inside the container hence you are getting the403
errorthe command should be
from host machine you can access the app on port 8080, i.e:
127.0.0.1:5000/data
# access from inside containerI just noticed, you didn’t expose the app on internet/external use, in the last line of your Dockerfile add arg "–host=0.0.0.0"
after docker build and publishing the port you should be able to access the app.