i try to run fastapi application with docker
i create this Dockerfile
FROM python
WORKDIR /code
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
COPY . /code/
CMD ["uvicorn", "blog.main:app"]
and run it with
docker run -p 8000:8000
the log says the application run on 127.0.0.1:8000 but i can’t access the application on http://localhost:8000
i create docker compose like this
services:
web:
build: .
command: uvicorn blog.main:app --reload --workers 1 --host 0.0.0.0 --port 8000
ports:
- "8000:8000"
and remove the CMD from Dockerfile and again have same log message application running at 127.0.0.1:8000 but this time i can access my application via http://localhost:8000
can someone explain whats wrong with my first method ?
2
Answers
You do not want the application listening on 127.0.0.1:8000. You want it listening on 0.0.0.0:8000 (as the second version is). I am not familiar with the program you are running, but there must be some way to tell it the host to listen on.
When a server binds to localhost (127.0.0.1), it accepts connections only from that machine. (The client also has to use localhost, not the actual IP address.) Since to docker, the host machine is a different machine, the connection is not allowed.
In docker-compose you are overriding the
CMD
with correct way of exposing thehost
and port to outside world. In your Dockerfile changeCMD ["uvicorn", "blog.main:app"]
toCMD ["uvicorn", "blog.main:app", "--host", "0.0.0.0", "--port", "8000"]
docker run should work