docker部署fastapi

项目结构:
pycharm结构:

docker部署fastapi_第1张图片

拷贝到xftp时的结构 

docker部署fastapi_第2张图片

入口文件:main.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/index", name="欢迎首页")
async def index():
    return {"msg": "欢迎来到SayHello!"}

项目依赖:

具体内容可以通过pip list 命令看到:docker部署fastapi_第3张图片

requirements.txt文件可以通过一下方法获取:

if __name__ == '__main__':
    popen = os.popen('pip list')
    with open('requirements.txt', 'w') as f:
        for index, i in enumerate(popen):
            if index > 1:
                split = re.findall('[a-z,.,0-9]*\S', i)
                k = split[0].strip()
                v = split[-1].strip()
                f.write(k + "==" + v + '\n')

requirements.txt 内容如下

aiofiles==0.5.0
aniso8601==7.0.0
async-exit-stack==1.0.1
async-generator==1.10
certifi==2021.5.30
charset-normalizer==2.0.3
click==7.1.2
colorama==0.4.4
dnspython==2.1.0
email-validator==1.1.3
fastapi==0.67.0
graphene==2.1.9
graphql-core==2.3.2
graphql-relay==2.0.1
h11==0.12.0
idna==3.2
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==2.0.1
orjson==3.6.0
pip==21.2.1
promise==2.3
pydantic==1.8.2
python-dotenv==0.19.0
python-multipart==0.0.5
PyYAML==5.4.1
requests==2.26.0
Rx==1.6.1
setuptools==57.4.0
six==1.16.0
starlette==0.14.2
typing-extensions==3.10.0.0
ujson==4.0.2
urllib3==1.26.6
uvicorn==0.13.4
watchgod==0.7
websockets==8.1

Dockerfile:

FROM python:3.9.5
COPY . /app
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone
WORKDIR ./app
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

xshell进入项目文件列表路径

构建镜像文件(命令结尾的小点“.” 别忘记了

docker build -t 项目名称 .

构建成功后运行容器即可:

docker run -d --name 新取的容器名称 -p 8000:80 刚刚构建的镜像名称

你可能感兴趣的:(python,docker,fastapi,python)