简体   繁体   English

docker 运行不起作用,但 docker 编写工作正常

[英]docker run won't work but docker compose work fine

i try to run fastapi application with docker i create this Dockerfile我尝试使用 docker 运行 fastapi 应用程序我创建了这个 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日志显示应用程序在 127.0.0.1:8000 上运行,但我无法访问 http://localhost:8000 上的应用程序

i create docker compose like this我创建 docker 像这样组成

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并从Dockerfile 中删除 CMD再次在 127.0.0.1:8000 运行相同的日志消息应用程序,但这次我可以通过 Z80791B3AE7002CB88C2468786D009A 访问我的应用程序:

can someone explain whats wrong with my first method?有人可以解释我的第一种方法有什么问题吗?

In docker-compose you are overriding the CMD with correct way of exposing the host and port to outside world.在 docker-compose 中,您将使用正确的方式将host和端口暴露给外界来覆盖CMD In your Dockerfile change CMD ["uvicorn", "blog.main:app"] to CMD ["uvicorn", "blog.main:app", "--host", "0.0.0.0", "--port", "8000"] docker run should work在您的 Dockerfile 中,将CMD ["uvicorn", "blog.main:app"]更改为CMD ["uvicorn", "blog.main:app", "--host", "0.0.0.0", "--port", "8000"] docker 运行应该可以

You do not want the application listening on 127.0.0.1:8000.您不希望应用程序监听 127.0.0.1:8000。 You want it listening on 0.0.0.0:8000 (as the second version is).您希望它在 0.0.0.0:8000 上监听(就像第二个版本一样)。 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.当服务器绑定到 localhost (127.0.0.1) 时,它只接受来自该机器的连接。 (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. (客户端也必须使用localhost,而不是实际的IP地址。)由于到docker,主机是不同的机器,不允许连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM