Home > Enterprise >  Docker container ports setup incorrectly
Docker container ports setup incorrectly

Time:11-24

I have a simple application I want to dockerize. It is a simple API that works correctly when I run it on my machine and is accessible on http://127.0.0.1:8000/ This is the dockerfile I created

FROM python:3.6-slim-stretch
WORKDIR /code
COPY requirements.txt /code
RUN pip install -r requirements.txt --no-cache-dir
COPY . /code
CMD ["uvicorn", "main:app", "--reload"]

I then create the image using this command sudo docker build -t test .

And then run it this way sudo docker run -d -p 8000:8000 test

The problem is that I cant access it http://127.0.0.1:8000/ even though I don't know the problem

PS: when I check my container ports I get 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp

I want to know what is causing this problem and how to fix it.

CodePudding user response:

By default uvicorn listens on 127.0.0.1. 127.0.0.1 inside the container is private,it doesn't participate in portforwarding.

The solution is to do uvicorn --host 0.0.0.0, e.g.:

CMD ["uvicorn", "main:app", "--reload", "--host", "0.0.0.0"]

For an explanation of why this is the case, with diagrams, see https://pythonspeed.com/articles/docker-connection-refused/

CodePudding user response:

  1. Try accessing http://0.0.0.0:8000
  2. What do you mean "I can access it"? Do you get permission denied? 404? what error are you seeing?
  3. Try accessing inside the container: $docker exec -it test bash and see if the program is running inside of it: $curl http://0.0.0.0:8000.
  4. Try curling into the container's explicit ip. get the ip: docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' test
  • Related