Docker部署SayHello(FastAPI)

1,077 阅读3分钟

目录

前言

昨天发了一个SayHello FastAPI版本,今天部署上自己的服务器了
体验地址: http://49.232.203.244:9001/message.html

服务部署

前置条件:以下在centos7.5 云服务器实验通过

yum -y install git	# 安装git
curl -sSL https://get.daocloud.io/docker | sh	# 安装docker

git clone gitee.com/zy7y/sayhel…

git clone github.com/zy7y/sayhel…

上面两个命令选一个执行就可了

部署后端

1. 进入到sayhello目录

cd sayhello

2. 编写API的Dockerfile(如果有请之直接构建镜像- 在下一步)

在sayhello目录下新建如下Dockerfile

FROM python:3.7
COPY . /app
WORKDIR ./app
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
EXPOSE 80
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

简单说下上面内容做了什么事情,不一定正确加了些个人理解

FROM python:3.7		# 拉取基础镜像python3.7,本机已有该镜像就会使用该镜像,没有就去远端仓库拉取,速度慢就需要换下源地址,百度即可(这里应该就是拉下镜像后弄成了个容器)
COPY . /app		# 将当前所在目录下所有文件 复制到 容器里面 /app 目录下
WORKDIR ./app	# 指定工作目录,我的理解是后面执行的命令 都相当于在这个目录下执行了,根目录的形式吧
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/	# 这步是在容器里面执行 pip 安装依赖
EXPOSE 80	# 将容器中80 端口开放
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]	# 容器运行时将执行 uvicorn main:app --host 0.0.0.0 --port 80 启动服务

3. 构建镜像

docker build -t sayhello .

4. 运行容器

会自动执行dockerfile里面的CMD命令

docker run -d --name sayhello-fastapi -p 8000:80 sayhello

5. 访问IP:8000/message,得到如下页面

部署前端

先确认message.html中的baseURL是不是后端服务的IP地址(127.0.0.1 不行)

1. 进入到sayhello/static目录

cd sayhello/static/

2. 编写Dockerfile文件(如果有请直接进入第三步)

FROM nginx:1.15.2-alpine
COPY . /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

3. 构建镜像

docker build -t sayhello-front .

4. 启动容器

docker run -d --name sayhello-front-9000 -p 9001:80 sayhello-front

5. 访问IP:9001/message.html

参考资料及感谢

感谢资料提供者/作者

  1. aqzt.com/bubble/6513…
  2. www.cnblogs.com/tian8745409…
  3. www.runoob.com/docker/dock…