Docker
部署FastAPI
FastAPI
是什么?官网链接(中文)
FastAPI
是一个用于构建API
的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
对比
Tornado
呢?相当于
Golang(Go)
语言中,Beego
与Gin
两个库的区别。如果是快速构建应用的话,那么Tornado
是非常推荐的。因为Tornado
采用Epoll
模型,性能上压根不用操心,再者用其开发web应用也有着非常便捷的优势。而FastAPI
和名字一样,偏重点在API
服务上,在加上有着自动化接口文档Swagger
优势非常明显(Tornado
开发API
也行,但没有Swagger
接口文档,较为乏力)。快速构建WEB --> Tornado 重构某一接口或构建API服务 --> FastAPI
如果是全新的
Ubuntu
系统,请先更新一下apt
,但是更新速度慢需要加速一下gedit /etc/apt/sources.list
然后在文件里复制粘贴一下
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial main restricted deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates main restricted deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial universe deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates universe deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial multiverse deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates multiverse deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security main restricted deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security universe deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security multiverse
好了,现在可以开始更新了
sudo apt update
如果要顺带更新一下已安装的包
sudo apt upgrade
现在,就是在
Ubuntu
上安装Docker
sudo apt install docker.io
添加加速源,不然拉取镜像走不动(image镜像在
docker
官方社区中,速度慢)tee /etc/docker/daemon.json <<- 'EOF' { "registry-mirrors": ["https://5xcgs6ii.mirror.aliyuncs.com"] } EOF
装完之后,建议重启一下系统,然后将服务启动开。
sudo systemctl start docker
环境准备好了,还有
Docker
镜像需要pull
docker pull daocloud.io/library/centos:7
这个
Docker
镜像是从daocloud
上拉取下来的。如果需要查看,也有链接。daocloud上的centos7容器
现在进入到项目的同级下,创建
dockerfile
文件# from Images tiangolo/uvicorn-gunicorn-fastapi:python3.7 FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 MAINTAINER Auther YourAccount = YourGithubLink # Adjust the time RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime # Copy files to target file. COPY ./app /app # Install library RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ crc16 RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ aliyun-python-sdk-core
Adjust the time
这个是我写过的解决Docker容器时间不准确一个方案,也就是更改Linux
系统的时间分区。
COPY ./app /app
将你项目文件夹下的所有文件拷贝到/app
中,而/app
文件夹本身就存在于镜像中。
RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ crc16
是我的项目需要crc16
库来对数据进行校验和。
RUN pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ aliyun-python-sdk-core
是阿里云Python
的SDK
。接下来就是制作镜像了
docker build -t ProjectName .
记得写上镜像名!
当镜像制作好了之后,我们可以根据镜像来拉起一个容器
docker run -itd --name NewProjectName -p 80:80 ProjectName
外部端口可以改变,毕竟
80
端口一般都是Nginx
组件在占用着。而内部端口,就不需要更改了。
ProjectName
就是刚刚我们制作的镜像名,而NewProjectName
是对容器命名,别搞混淆了。
访问
Swagger
文档路径localhost/docs
访问另一个文档路径
localhost/redoc
如果还有什么问题,可以在文章下边留言,博主尽能力之内给大家解答一下。