項目結構:
pycharm結構:
拷貝到xftp時的結構
入口文件:main.py
from fastapi import FastAPI app = FastAPI() @app.get("/index", name="歡迎首頁") async def index(): return {"msg": "歡迎來到SayHello!"}
項目依賴:
使用命令可以直接在根目錄生成requirements.txt文件
pip freeze > requirements.txt
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 剛剛構建的鏡像名稱