前言:因为遇到了docker+etcd 无法远程访问?这个问题,所以我要深入探究一下


当容器内的进程只监听 127.0.0.1 而不是 0.0.0.0 ,宿主机可以使用 127.0.0.1 访问资源吗?可以

当容器内的进程只监听 127.0.0.1 而不是 0.0.0.0 ,宿主机可以使用 网关分配的ip 访问资源吗?不可以

网关分配的ip 指的是 192.168.x.1 这种

下面做一个实验

FROM python:3.10.10-bullseye 
RUN echo "deb http://mirrors.aliyun.com/debian/ bullseye main non-free contrib" > /etc/apt/sources.list

RUN apt-get update
RUN apt-get install -y vim netcat telnet less sysstat htop ncdu

RUN mkdir /code
WORKDIR /code

COPY requirements-dev.txt /code/
RUN pip install -r requirements-dev.txt -i https://mirror.baidu.com/pypi/simple

COPY requirements-prd.txt /code/
RUN pip install -r requirements-prd.txt -i https://mirror.baidu.com/pypi/simple


ADD . /code/

requirements-dev.txt

mycli
ipython
autopep8
psutil
glances
pylint

requirements-prd.txt

pymilvus==2.2.8
numpy 
pydantic<2.0.0
loguru 
requests 
pyyaml 
python-dotenv 
python-multipart  # Form data requires "python-multipart" to be installed.
cryptography
pymysql 
peewee 
oss2 
fastapi 
uvicorn 
psutil
dnspython==2.2.1

api.py

from fastapi import FastAPI, Form, Request
from loguru import logger
import uvicorn
from fastapi import FastAPI, Form, Depends, Request

app = FastAPI()


async def get_form(request: Request):
    form_data = await request.form()
    return dict(form_data)


@app.post('/search')
def search_reverse(
    request: Request,
    form_data: dict = Depends(get_form),
    max_chunk_size: int = Form(1200, description='分批查询 milvus,每个查询批次的向量个数'),
    search_top_k: int = Form(
        default=30, description='搜索 milvus 的时候,返回的最相似的 N 个结果'),
    distance_threshold: float = Form(
        0.32, description='距离上限(距离使用 L2 欧氏距离衡量,越接近 0 越相似),但 milvus 的搜索结果返回后,丢弃大于该值的向量搜索结果')
):
    form_dict = dict(form_data)
    logger.debug(form_dict)


if __name__ == "__main__":
    uvicorn.run(
        app='api:app',
        host="127.0.0.1",
        port=9950,
        workers=1,
        reload=True
    )

打包镜像

docker build -t "ponponon/fastapi_example" .

运行镜像

docker run -p 9950:9950 --rm -it ponponon/fastapi_example python api.py

使用 nc 命令探测端口是否开放

─➤  nc -zv 192.168.2.15 9950                                                                         130 ↵
nc: connect to 192.168.2.15 port 9950 (tcp) failed: Connection refused
─➤  nc -zv 127.0.0.1 9950                                                                              1 ↵
Connection to 127.0.0.1 9950 port [tcp/*] succeeded!

universe_king
3.4k 声望678 粉丝